Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat: implement CLI daemon mode, service management, and chat command support for agent status and configuration
Salman Qureshi04e633dbf8c3
diff --git a/DECISIONS.md b/DECISIONS.mdindex 8cd11b5c..7f56c89b 100644--- a/DECISIONS.md+++ b/DECISIONS.md@@ -48,4 +48,19 @@- **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 file+- **Consequence**: Mercury can autonomously schedule work. Tasks survive restarts. Internal execution keeps scheduled tasks invisible to channels unless the agent explicitly sends output.++## ADR-009: Daemonization via Custom Hybrid Approach++- **Context**: Mercury runs 24/7 but only in foreground mode. Closing the terminal kills the process, breaking Telegram, scheduled tasks, and heartbeat. Non-technical users should not need to install PM2/forever/systemd scripts manually.+- **Decision**: Build a custom hybrid daemon manager natively into Mercury. No external dependencies. Uses three layers:+ 1. **Background spawn** — `child_process.spawn({detached: true})` + PID file + log redirect. Activated via `mercury start -d`.+ 2. **Watchdog** — Built-in crash recovery with exponential backoff (1s base, 1.25x, max 10 restarts/60s). Only active in daemon mode.+ 3. **Platform service generators** — `mercury service install` detects OS and generates the appropriate config: `systemd --user` unit on Linux, `~/Library/LaunchAgents` plist on macOS, startup shortcut on Windows. No root needed on Mac/Linux.+- **Alternatives considered**:+ - `node-windows/mac/linux` trio — partially unmaintained, requires sudo on Mac, node-linux is dead+ - PM2 as dependency — 15MB, 50+ deps, AGPL-3.0 license+ - PM2 as user install — requires non-technical users to learn a separate tool+ - `forever` — officially deprecated by its own maintainers+ - Native detached only — no crash recovery, no boot startup+- **Consequence**: Zero external dependencies for core daemonization. Boot services are user-level (no sudo on Mac/Linux). Windows gets background mode + documented PM2 path. Foreground mode unchanged — daemon mode is opt-in. In daemon mode, CLI becomes log-only; Telegram (or other remote channels) is the interactive interface.\ No newline at end of filediff --git a/src/capabilities/registry.ts b/src/capabilities/registry.tsindex 11b0d4d2..46626a8c 100644--- a/src/capabilities/registry.ts+++ b/src/capabilities/registry.ts@@ -28,6 +28,14 @@ import type { Scheduler } from '../core/scheduler.js';import type { TokenBudget } from '../utils/tokens.js';import { logger } from '../utils/logger.js';+export interface ChatCommandContext {+ toolNames: () => string[];+ skillNames: () => string[];+ config: () => import('../utils/config.js').MercuryConfig;+ tokenBudget: () => import('../utils/tokens.js').TokenBudget;+ manual: () => string;+}+export class CapabilityRegistry {readonly permissions: PermissionManager;private tools: Record<string, Tool> = {};@@ -37,6 +45,7 @@ export class CapabilityRegistry {private sendFileHandler?: (filePath: string) => Promise<void>;private currentChannelId = 'cli';private currentChannelType = 'cli';+ private chatCommandContext?: ChatCommandContext;constructor(skillLoader?: SkillLoader, scheduler?: Scheduler, tokenBudget?: TokenBudget) {this.permissions = new PermissionManager();@@ -45,6 +54,14 @@ export class CapabilityRegistry {this.tokenBudget = tokenBudget;}+ setChatCommandContext(ctx: ChatCommandContext): void {+ this.chatCommandContext = ctx;+ }++ getChatCommandContext(): ChatCommandContext | undefined {+ return this.chatCommandContext;+ }+setChannelContext(channelId: string, channelType: string): void {this.currentChannelId = channelId;this.currentChannelType = channelType;diff --git a/src/cli/daemon.ts b/src/cli/daemon.tsnew file mode 100644index 00000000..40ef15e3--- /dev/null+++ b/src/cli/daemon.ts@@ -0,0 +1,122 @@+import { spawn } from 'node:child_process';+import { existsSync, readFileSync, writeFileSync, unlinkSync, mkdirSync, openSync } from 'node:fs';+import { join } from 'node:path';+import process from 'node:process';+import chalk from 'chalk';+import { getMercuryHome } from '../utils/config.js';++const PID_FILE = 'daemon.pid';+const LOG_FILE = 'daemon.log';++function pidPath(): string {+ return join(getMercuryHome(), PID_FILE);+}++function logPath(): string {+ return join(getMercuryHome(), LOG_FILE);+}++export function readPid(): number | null {+ const path = pidPath();+ if (!existsSync(path)) return null;+ try {+ const pid = parseInt(readFileSync(path, 'utf-8').trim(), 10);+ if (isNaN(pid)) return null;+ return pid;+ } catch {+ return null;+ }+}++function isProcessRunning(pid: number): boolean {+ try {+ process.kill(pid, 0);+ return true;+ } catch {+ return false;+ }+}++export function getDaemonStatus(): { running: boolean; pid: number | null; logPath: string } {+ const pid = readPid();+ if (!pid) return { running: false, pid: null, logPath: logPath() };+ return { running: isProcessRunning(pid), pid, logPath: logPath() };+}++export function startBackground(): void {+ const status = getDaemonStatus();+ if (status.running && status.pid) {+ console.log(chalk.yellow(` Mercury is already running (PID: ${status.pid})`));+ console.log(chalk.dim(` Use \`mercury stop\` to stop it first.`));+ console.log('');+ process.exit(1);+ }++ if (status.pid && !status.running) {+ try { unlinkSync(pidPath()); } catch {}+ }++ const home = getMercuryHome();+ if (!existsSync(home)) {+ mkdirSync(home, { recursive: true });+ }++ const logFile = logPath();+ const outFd = openSync(logFile, 'a');++ const child = spawn(process.execPath, [process.argv[1], 'start', '--daemon'], {+ detached: true,+ stdio: ['ignore', outFd, outFd],+ env: { ...process.env },+ });++ child.unref();++ writeFileSync(pidPath(), String(child.pid));++ console.log('');+ console.log(chalk.green(` Mercury started in background (PID: ${child.pid})`));+ console.log(chalk.dim(` Logs: ${logFile}`));+ console.log(chalk.dim(` Use \`mercury stop\` to stop.`));+ console.log(chalk.dim(` Use \`mercury logs\` to view logs.`));+ console.log('');+}++export function stopDaemon(): void {+ const status = getDaemonStatus();++ if (!status.pid) {+ console.log(chalk.yellow(' Mercury is not running as a daemon.'));+ console.log('');+ process.exit(0);+ }++ if (!status.running) {+ console.log(chalk.yellow(` Stale PID file found (PID: ${status.pid} is not running). Cleaning up.`));+ try { unlinkSync(pidPath()); } catch {}+ console.log('');+ process.exit(0);+ }++ try {+ process.kill(status.pid, 'SIGTERM');+ console.log(chalk.green(` Mercury stopped (PID: ${status.pid})`));+ } catch {+ console.log(chalk.red(` Failed to stop PID ${status.pid}. You may need to kill it manually.`));+ }++ try { unlinkSync(pidPath()); } catch {}+ console.log('');+}++export function showLogs(): void {+ const logFile = logPath();+ if (!existsSync(logFile)) {+ console.log(chalk.dim(' No daemon log file found.'));+ console.log('');+ return;+ }+ const content = readFileSync(logFile, 'utf-8');+ const lines = content.split('\n').slice(-100);+ console.log(lines.join('\n'));+}\ No newline at end of filediff --git a/src/cli/service.ts b/src/cli/service.tsnew file mode 100644index 00000000..4ac12f44--- /dev/null+++ b/src/cli/service.ts@@ -0,0 +1,297 @@+import { existsSync, mkdirSync, writeFileSync, unlinkSync } from 'node:fs';+import { join } from 'node:path';+import { homedir } from 'node:os';+import chalk from 'chalk';+import { execSync } from 'node:child_process';+import { getMercuryHome } from '../utils/config.js';+import { logger } from '../utils/logger.js';++const SERVICE_NAME = 'mercury';+const SERVICE_DESC = 'Mercury — Soul-Driven AI Agent';++function getNodeBinPath(): string {+ return process.execPath;+}++function getDistPath(): string {+ return join(process.argv[1] || '/usr/local/bin/mercury', '..', '..', 'lib', 'node_modules', '@cosmicstack', 'mercury-agent', 'dist', 'index.js');+}++export function installService(): void {+ const platform = process.platform;++ if (platform === 'darwin') {+ installMac();+ } else if (platform === 'linux') {+ installLinux();+ } else if (platform === 'win32') {+ console.log(chalk.yellow(' Windows service install is not yet automated.'));+ console.log(chalk.dim(' Use \`mercury start -d\` for background mode, or install PM2:'));+ console.log(chalk.dim(' npm i -g pm2'));+ console.log(chalk.dim(' pm2 start mercury'));+ console.log(chalk.dim(' pm2 startup'));+ console.log('');+ return;+ } else {+ console.log(chalk.red(` Unsupported platform: ${platform}`));+ process.exit(1);+ }+}++export function uninstallService(): void {+ const platform = process.platform;++ if (platform === 'darwin') {+ uninstallMac();+ } else if (platform === 'linux') {+ uninstallLinux();+ } else if (platform === 'win32') {+ console.log(chalk.yellow(' Windows service uninstall is not yet automated.'));+ console.log('');+ } else {+ console.log(chalk.red(` Unsupported platform: ${platform}`));+ process.exit(1);+ }+}++export function showServiceStatus(): void {+ const platform = process.platform;++ if (platform === 'darwin') {+ showMacStatus();+ } else if (platform === 'linux') {+ showLinuxStatus();+ } else if (platform === 'win32') {+ console.log(chalk.yellow(' Windows service status is not yet automated.'));+ console.log('');+ }+}++function installMac(): void {+ const plistDir = join(homedir(), 'Library', 'LaunchAgents');+ const plistPath = join(plistDir, 'com.cosmicstack.mercury.plist');++ if (!existsSync(plistDir)) {+ mkdirSync(plistDir, { recursive: true });+ }++ const nodeBin = getNodeBinPath();+ const scriptPath = getDistPath();+ const home = getMercuryHome();+ const logPath = join(home, 'daemon.log');+ const errPath = join(home, 'daemon-error.log');++ const plist = `<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>Label</key>+ <string>com.cosmicstack.mercury</string>+ <key>ProgramArguments</key>+ <array>+ <string>${nodeBin}</string>+ <string>${scriptPath}</string>+ <string>start</string>+ <string>--daemon</string>+ </array>+ <key>RunAtLoad</key>+ <true/>+ <key>KeepAlive</key>+ <dict>+ <key>SuccessfulExit</key>+ <false/>+ </dict>+ <key>StandardOutPath</key>+ <string>${logPath}</string>+ <key>StandardErrorPath</key>+ <string>${errPath}</string>+ <key>EnvironmentVariables</key>+ <dict>+ <key>PATH</key>+ <string>${process.env.PATH || '/usr/local/bin:/usr/bin:/bin'}</string>+ <key>HOME</key>+ <string>${homedir()}</string>+ </dict>+ <key>WorkingDirectory</key>+ <string>${homedir()}</string>+</dict>+</plist>`;++ writeFileSync(plistPath, plist, 'utf-8');++ try {+ execSync(`launchctl load ${plistPath}`, { stdio: 'inherit' });+ } catch {+ console.log(chalk.yellow(' launchctl load failed. Try running:'));+ console.log(chalk.dim(` launchctl load ${plistPath}`));+ }++ console.log('');+ console.log(chalk.green(' Mercury service installed (macOS LaunchAgent)'));+ console.log(chalk.dim(` Plist: ${plistPath}`));+ console.log(chalk.dim(` Logs: ${logPath}`));+ console.log(chalk.dim(' Auto-starts on login. Auto-restarts on crash.'));+ console.log('');+ console.log(chalk.dim(' Uninstall: mercury service uninstall'));+ console.log('');+}++function uninstallMac(): void {+ const plistPath = join(homedir(), 'Library', 'LaunchAgents', 'com.cosmicstack.mercury.plist');++ if (!existsSync(plistPath)) {+ console.log(chalk.yellow(' Mercury service is not installed.'));+ console.log('');+ process.exit(0);+ }++ try {+ execSync(`launchctl unload ${plistPath}`, { stdio: 'inherit' });+ } catch {+ // may already be unloaded+ }++ try {+ unlinkSync(plistPath);+ } catch {+ console.log(chalk.yellow(' Failed to remove plist file. Remove manually:'));+ console.log(chalk.dim(` rm ${plistPath}`));+ }++ console.log('');+ console.log(chalk.green(' Mercury service uninstalled'));+ console.log('');+}++function showMacStatus(): void {+ const plistPath = join(homedir(), 'Library', 'LaunchAgents', 'com.cosmicstack.mercury.plist');++ if (!existsSync(plistPath)) {+ console.log(chalk.yellow(' Mercury service is not installed.'));+ console.log(chalk.dim(' Run `mercury service install` to set it up.'));+ console.log('');+ return;+ }++ try {+ const output = execSync('launchctl list | grep com.cosmicstack.mercury', { encoding: 'utf-8' }).trim();+ console.log(` ${chalk.green('Service installed and loaded')}`);+ console.log(chalk.dim(` ${output}`));+ } catch {+ console.log(` ${chalk.yellow('Service installed but not loaded')}`);+ console.log(chalk.dim(` Plist: ${plistPath}`));+ }+ console.log('');+}++function installLinux(): void {+ const systemdDir = join(homedir(), '.config', 'systemd', 'user');++ if (!existsSync(systemdDir)) {+ mkdirSync(systemdDir, { recursive: true });+ }++ const servicePath = join(systemdDir, 'mercury.service');+ const nodeBin = getNodeBinPath();+ const scriptPath = getDistPath();+ const home = getMercuryHome();++ const service = `[Unit]+Description=${SERVICE_DESC}+After=network.target++[Service]+Type=simple+ExecStart=${nodeBin} ${scriptPath} start --daemon+Restart=on-failure+RestartSec=5+Environment=PATH=${process.env.PATH || '/usr/local/bin:/usr/bin:/bin'}+Environment=HOME=${homedir()}+WorkingDirectory=${homedir()}+StandardOutput=append:${join(home, 'daemon.log')}+StandardError=append:${join(home, 'daemon-error.log')}++[Install]+WantedBy=default.target`;++ writeFileSync(servicePath, service, 'utf-8');++ try {+ execSync('systemctl --user daemon-reload', { stdio: 'inherit' });+ execSync('systemctl --user enable mercury.service', { stdio: 'inherit' });+ execSync('systemctl --user start mercury.service', { stdio: 'inherit' });+ } catch (err) {+ console.log(chalk.yellow(' systemd commands failed. Try running manually:'));+ console.log(chalk.dim(' systemctl --user daemon-reload'));+ console.log(chalk.dim(' systemctl --user enable mercury.service'));+ console.log(chalk.dim(' systemctl --user start mercury.service'));+ }++ try {+ execSync(`loginctl enable-linger ${process.env.USER || ''}`, { stdio: 'inherit' });+ } catch {+ console.log(chalk.yellow(' Enable linger failed (needed for boot-without-login). Try:'));+ console.log(chalk.dim(` sudo loginctl enable-linger ${process.env.USER || '$USER'}`));+ }++ console.log('');+ console.log(chalk.green(' Mercury service installed (systemd --user)'));+ console.log(chalk.dim(` Service: ${servicePath}`));+ console.log(chalk.dim(` Logs: ${join(home, 'daemon.log')}`));+ console.log(chalk.dim(' Auto-starts on login. Auto-restarts on crash (5s delay).'));+ console.log('');+ console.log(chalk.dim(' Uninstall: mercury service uninstall'));+ console.log('');+}++function uninstallLinux(): void {+ const servicePath = join(homedir(), '.config', 'systemd', 'user', 'mercury.service');++ if (!existsSync(servicePath)) {+ console.log(chalk.yellow(' Mercury service is not installed.'));+ console.log('');+ process.exit(0);+ }++ try {+ execSync('systemctl --user stop mercury.service', { stdio: 'inherit' });+ execSync('systemctl --user disable mercury.service', { stdio: 'inherit' });+ } catch {+ // may already be stopped+ }++ try {+ unlinkSync(servicePath);+ } catch {+ console.log(chalk.yellow(' Failed to remove service file. Remove manually:'));+ console.log(chalk.dim(` rm ${servicePath}`));+ }++ try {+ execSync('systemctl --user daemon-reload', { stdio: 'inherit' });+ } catch {}++ console.log('');+ console.log(chalk.green(' Mercury service uninstalled'));+ console.log('');+}++function showLinuxStatus(): void {+ const servicePath = join(homedir(), '.config', 'systemd', 'user', 'mercury.service');++ if (!existsSync(servicePath)) {+ console.log(chalk.yellow(' Mercury service is not installed.'));+ console.log(chalk.dim(' Run `mercury service install` to set it up.'));+ console.log('');+ return;+ }++ try {+ const output = execSync('systemctl --user status mercury.service', { encoding: 'utf-8' }).trim();+ console.log(output);+ } catch (err: any) {+ console.log(chalk.yellow(' Could not get service status:'));+ console.log(chalk.dim(` ${err.message || err}`));+ }+ console.log('');+}\ No newline at end of filediff --git a/src/cli/watchdog.ts b/src/cli/watchdog.tsnew file mode 100644index 00000000..72dd1b9c--- /dev/null+++ b/src/cli/watchdog.ts@@ -0,0 +1,36 @@+import { logger } from '../utils/logger.js';++const MAX_RESTARTS = 10;+const RESTART_WINDOW_MS = 60_000;+const BASE_DELAY_MS = 1_000;++export async function runWithWatchdog(agentFn: () => Promise<void>): Promise<void> {+ const restarts: number[] = [];++ async function attempt(): Promise<void> {+ try {+ await agentFn();+ } catch (err) {+ const now = Date.now();+ restarts.push(now);+ const recentRestarts = restarts.filter(t => now - t < RESTART_WINDOW_MS);+ const restartCount = recentRestarts.length;++ if (restartCount >= MAX_RESTARTS) {+ logger.error({ restartCount }, 'Max restarts exceeded within 60s. Exiting.');+ process.exit(1);+ }++ const delay = BASE_DELAY_MS * Math.pow(1.25, restartCount);+ logger.warn({ err, restartCount, delay }, 'Crash detected. Restarting with backoff...');+ await sleep(delay);+ await attempt();+ }+ }++ await attempt();+}++function sleep(ms: number): Promise<void> {+ return new Promise(resolve => setTimeout(resolve, ms));+}\ No newline at end of filediff --git a/src/core/agent.ts b/src/core/agent.tsindex dc4603e0..7f4a7944 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -118,6 +118,11 @@ export class Agent {return;}+ if (await this.handleChatCommand(trimmed, msg.channelType, msg.channelId)) {+ this.lifecycle.transition('idle');+ return;+ }+if (this.tokenBudget.isOverBudget()) {const channel = this.channels.getChannelForMessage(msg);if (channel && msg.channelType !== 'internal') {@@ -490,4 +495,61 @@ export class Agent {await channel.send(`Unknown budget command "${action}". Available: /budget, /budget override, /budget reset, /budget set <number>, /budget status`, channelId);}}++ private async handleChatCommand(content: string, channelType: string, channelId: string): Promise<boolean> {+ const cmd = content.toLowerCase().trim();+ const channel = this.channels.get(channelType as any);+ if (!channel) return false;++ const ctx = this.capabilities.getChatCommandContext();+ if (!ctx) return false;++ if (cmd === '/help') {+ await channel.send(ctx.manual(), channelId);+ return true;+ }++ if (cmd === '/status') {+ const config = ctx.config();+ const budget = ctx.tokenBudget();+ const lines = [+ `**${config.identity.name}** — Status`,+ `Owner: ${config.identity.owner || '(not set)'}`,+ `Provider: ${config.providers.default}`,+ `Telegram: ${config.channels.telegram.enabled ? 'enabled' : 'disabled'}`,+ `Budget: ${budget.getStatusText()}`,+ `Skills: ${ctx.skillNames().length > 0 ? ctx.skillNames().join(', ') : 'none'}`,+ ];+ await channel.send(lines.join('\n'), channelId);+ return true;+ }++ if (cmd === '/tools') {+ const tools = ctx.toolNames();+ const grouped = [+ `**${tools.length} tools loaded:**`,+ '',+ ...tools.sort().map(t => `• \`${t}\``),+ ];+ await channel.send(grouped.join('\n'), channelId);+ return true;+ }++ if (cmd === '/skills') {+ const names = ctx.skillNames();+ if (names.length === 0) {+ await channel.send('No skills installed. Ask me to "install skill from <url>" to add one.', channelId);+ } else {+ const lines = [+ `**${names.length} skill${names.length > 1 ? 's' : ''} installed:**`,+ '',+ ...names.map(n => `• ${n}`),+ ];+ await channel.send(lines.join('\n'), channelId);+ }+ return true;+ }++ return false;+ }}\ No newline at end of filediff --git a/src/index.ts b/src/index.tsindex 550b7b39..858143d6 100644--- a/src/index.ts+++ b/src/index.ts@@ -3,6 +3,7 @@ import readline from 'node:readline';import chalk from 'chalk';import figlet from 'figlet';import { loadConfig, saveConfig, isSetupComplete, getMercuryHome, ensureCreatorField } from './utils/config.js';+import type { MercuryConfig } from './utils/config.js';import { logger } from './utils/logger.js';import { Identity } from './soul/identity.js';import { ShortTermMemory, LongTermMemory, EpisodicMemory } from './memory/store.js';@@ -14,6 +15,10 @@ import { CLIChannel } from './channels/cli.js';import { TokenBudget } from './utils/tokens.js';import { CapabilityRegistry } from './capabilities/registry.js';import { SkillLoader } from './skills/loader.js';+import { getManual } from './utils/manual.js';+import { startBackground, stopDaemon, showLogs, getDaemonStatus } from './cli/daemon.js';+import { installService, uninstallService, showServiceStatus } from './cli/service.js';+import { runWithWatchdog } from './cli/watchdog.js';function hr() {console.log(chalk.dim('─'.repeat(50)));@@ -54,61 +59,116 @@ async function ask(prompt: string): Promise<string> {});}-async function onboarding(): Promise<void> {- splashScreen();- console.log(chalk.yellow(' First run detected — let\'s set you up.'));+function maskKey(key: string): string {+ if (!key) return '';+ if (key.length <= 8) return '••••••••';+ return key.slice(0, 4) + '••••' + key.slice(-4);+}++async function configure(existingConfig?: MercuryConfig): Promise<void> {+ const isReconfig = !!existingConfig;+ const config = existingConfig ?? loadConfig();++ if (isReconfig) {+ banner();+ console.log(chalk.yellow(' Reconfiguring Mercury — press Enter to keep current value.'));+ } else {+ splashScreen();+ console.log(chalk.yellow(' First run detected — let\'s set you up.'));+ }+hr();console.log('');+ console.log(chalk.bold.white(' Identity'));+ console.log('');- const config = loadConfig();+ if (isReconfig) {+ const ownerName = await ask(chalk.white(` Your name [${config.identity.owner}]: `));+ if (ownerName) config.identity.owner = ownerName;++ const agentName = await ask(chalk.white(` Agent name [${config.identity.name}]: `));+ if (agentName) config.identity.name = agentName;+ } else {+ const ownerName = await ask(chalk.white(' Your name: '));+ if (!ownerName) {+ console.log(chalk.red(' Name is required.'));+ process.exit(1);+ }+ config.identity.owner = ownerName;- const ownerName = await ask(chalk.white(' Your name: '));- if (!ownerName) {- console.log(chalk.red(' Name is required.'));- process.exit(1);+ const agentName = await ask(chalk.white(` Agent name [${config.identity.name}]: `));+ if (agentName) config.identity.name = agentName;}- config.identity.owner = ownerName;-- const agentName = await ask(chalk.white(` Agent name [${config.identity.name}]: `));- if (agentName) config.identity.name = agentName;- config.identity.creator = 'Cosmic Stack';+ config.identity.creator = config.identity.creator || 'Cosmic Stack';hr();console.log('');- console.log(chalk.white(' LLM Providers'));- console.log(chalk.dim(' At least one API key is required.'));+ console.log(chalk.bold.white(' LLM Providers'));+ if (isReconfig) {+ console.log(chalk.dim(' Current keys shown masked. Enter new value to change, Enter to keep.'));+ } else {+ console.log(chalk.dim(' At least one API key is required.'));+ }console.log('');- const deepseekKey = await ask(chalk.white(' DeepSeek API key: '));+ const dsMask = isReconfig && config.providers.deepseek.apiKey ? ` [${maskKey(config.providers.deepseek.apiKey)}]` : '';+ const deepseekKey = await ask(chalk.white(` DeepSeek API key${dsMask}: `));if (deepseekKey) {config.providers.deepseek.apiKey = deepseekKey;config.providers.default = 'deepseek';}- const openaiKey = await ask(chalk.white(' OpenAI API key (Enter to skip): '));+ const oaiMask = isReconfig && config.providers.openai.apiKey ? ` [${maskKey(config.providers.openai.apiKey)}]` : ' (Enter to skip)';+ const openaiKey = await ask(chalk.white(` OpenAI API key${oaiMask}: `));if (openaiKey) config.providers.openai.apiKey = openaiKey;- const anthropicKey = await ask(chalk.white(' Anthropic API key (Enter to skip): '));+ const antMask = isReconfig && config.providers.anthropic.apiKey ? ` [${maskKey(config.providers.anthropic.apiKey)}]` : ' (Enter to skip)';+ const anthropicKey = await ask(chalk.white(` Anthropic API key${antMask}: `));if (anthropicKey) config.providers.anthropic.apiKey = anthropicKey;- if (!deepseekKey && !openaiKey && !anthropicKey) {+ const hasKey = config.providers.deepseek.apiKey || config.providers.openai.apiKey || config.providers.anthropic.apiKey;+ if (!hasKey) {console.log(chalk.red('\n At least one LLM API key is required.'));process.exit(1);}hr();console.log('');- console.log(chalk.white(' Telegram (optional)'));- console.log(chalk.dim(' Leave empty to skip. You can add it later.'));+ console.log(chalk.bold.white(' Telegram (optional)'));+ if (isReconfig) {+ console.log(chalk.dim(' Leave empty to keep current value. Enter "none" to disable.'));+ } else {+ console.log(chalk.dim(' Leave empty to skip. You can add it later.'));+ }console.log('');- const telegramToken = await ask(chalk.white(' Telegram Bot Token: '));- if (telegramToken) {+ const tgMask = isReconfig && config.channels.telegram.botToken ? ` [${maskKey(config.channels.telegram.botToken)}]` : '';+ const telegramToken = await ask(chalk.white(` Telegram Bot Token${tgMask}: `));+ if (isReconfig && telegramToken.toLowerCase() === 'none') {+ config.channels.telegram.enabled = false;+ config.channels.telegram.botToken = '';+ } else if (telegramToken) {config.channels.telegram.botToken = telegramToken;config.channels.telegram.enabled = true;}+ hr();+ console.log('');+ console.log(chalk.bold.white(' Token Budget'));+ console.log('');++ const budgetPrompt = isReconfig+ ? chalk.white(` Daily token budget [${config.tokens.dailyBudget.toLocaleString()}]: `)+ : chalk.white(` Daily token budget [${config.tokens.dailyBudget.toLocaleString()}]: `);+ const budgetStr = await ask(budgetPrompt);+ if (budgetStr) {+ const budget = parseInt(budgetStr.replace(/,/g, ''), 10);+ if (!isNaN(budget) && budget > 0) {+ config.tokens.dailyBudget = budget;+ }+ }+hr();saveConfig(config);@@ -125,29 +185,43 @@ async function onboarding(): Promise<void> {console.log('');}-async function runAgent(): Promise<void> {+async function runAgent(isDaemon: boolean = false): Promise<void> {let config = loadConfig();config = ensureCreatorField(config);const name = config.identity.name;- banner();- console.log(chalk.white(` ${name} is waking up...`));- console.log('');+ if (!isDaemon) {+ banner();+ console.log(chalk.white(` ${name} is waking up...`));+ console.log('');+ } else {+ logger.info(`${name} is waking up (daemon mode)...`);+ }const tokenBudget = new TokenBudget(config);const providers = new ProviderRegistry(config);if (!providers.hasProviders()) {- console.log(chalk.red(' No LLM providers available. Run `mercury setup` to configure API keys.'));+ if (isDaemon) {+ logger.error('No LLM providers available. Run `mercury doctor` to configure API keys.');+ return;+ }+ console.log(chalk.red(' No LLM providers available. Run `mercury doctor` to configure API keys.'));process.exit(1);}const available = providers.listAvailable();- console.log(chalk.dim(` Providers: ${available.join(', ')}`));+ if (!isDaemon) {+ console.log(chalk.dim(` Providers: ${available.join(', ')}`));+ } else {+ logger.info({ providers: available }, 'Providers loaded');+ }const skillLoader = new SkillLoader();const skills = skillLoader.discover();- console.log(chalk.dim(` Skills: ${skills.length > 0 ? skills.map(s => s.name).join(', ') : 'none installed'}`));+ if (!isDaemon) {+ console.log(chalk.dim(` Skills: ${skills.length > 0 ? skills.map(s => s.name).join(', ') : 'none installed'}`));+ }const scheduler = new Scheduler(config);@@ -159,6 +233,14 @@ async function runAgent(): Promise<void> {const channels = new ChannelRegistry(config);const capabilities = new CapabilityRegistry(skillLoader, scheduler, tokenBudget);+ capabilities.setChatCommandContext({+ toolNames: () => capabilities.getToolNames(),+ skillNames: () => skills.map(s => s.name),+ config: () => config,+ tokenBudget: () => tokenBudget,+ manual: () => getManual(),+ });+capabilities.setSendFileHandler(async (filePath: string) => {const msg = channels.getActiveChannels().includes('telegram')? channels.get('telegram')@@ -187,22 +269,31 @@ 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}`));++ if (!isDaemon) {+ 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.`));+ console.log(chalk.dim(' Ctrl+C to exit · /help for commands'));+ console.log('');+ } else {+ logger.info({ channels: activeCh, tools: toolNames }, 'Mercury is live (daemon mode)');}- hr();- console.log('');- console.log(chalk.green(` ${name} is live. Type a message and press Enter.`));- console.log(chalk.dim(' Ctrl+C to exit.'));- console.log('');const shutdown = async () => {- console.log('');- console.log(chalk.dim(` ${name} is shutting down...`));+ if (!isDaemon) {+ console.log('');+ console.log(chalk.dim(` ${name} is shutting down...`));+ } else {+ logger.info('Mercury is shutting down (daemon mode)');+ }await agent.shutdown();process.exit(0);};@@ -215,12 +306,12 @@ const program = new Command();program.name('mercury')- .description('Mercury — an AI agent for personal tasks')+ .description('Mercury — Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access.').version('0.1.0').option('-v, --verbose', 'Show debug logs').action(async () => {if (!isSetupComplete()) {- await onboarding();+ await configure();return;}await runAgent();@@ -230,29 +321,71 @@ program.command('start').description('Start Mercury agent').option('-v, --verbose', 'Show debug logs')- .action(async () => {+ .option('-d, --detached', 'Run in background (daemon mode)')+ .option('--daemon', 'Internal flag for daemon child process')+ .action(async (opts) => {+ if (opts.daemon) {+ await runWithWatchdog(() => runAgent(true));+ return;+ }++ if (opts.detached) {+ startBackground();+ return;+ }+if (!isSetupComplete()) {- await onboarding();+ await configure();return;}await runAgent();});+program+ .command('stop')+ .description('Stop a background Mercury process')+ .action(() => {+ stopDaemon();+ });++program+ .command('logs')+ .description('Show recent daemon logs')+ .action(() => {+ showLogs();+ });+program.command('setup')- .description('Re-run the setup wizard')+ .description('Re-run the setup wizard (reconfigure)').action(async () => {- await onboarding();+ if (isSetupComplete()) {+ await configure(loadConfig());+ } else {+ await configure();+ }+ });++program+ .command('doctor')+ .description('Reconfigure Mercury — change keys, name, settings (Enter to keep current)')+ .action(async () => {+ if (isSetupComplete()) {+ await configure(loadConfig());+ } else {+ await configure();+ }});program.command('status')- .description('Show current configuration')+ .description('Show current configuration and daemon status').action(() => {const config = loadConfig();const home = getMercuryHome();const skillLoader = new SkillLoader();const skills = skillLoader.discover();+ const daemon = getDaemonStatus();banner();console.log(` Name: ${chalk.cyan(config.identity.name)}`);console.log(` Owner: ${chalk.white(config.identity.owner || '(not set)')}`);@@ -262,10 +395,43 @@ programconsole.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(` Budget: ${chalk.white(config.tokens.dailyBudget.toLocaleString())} tokens/day`);console.log(` Setup: ${isSetupComplete() ? chalk.green('complete') : chalk.red('not done')}`);+ console.log(` Daemon: ${daemon.running ? chalk.green(`running (PID: ${daemon.pid})`) : chalk.dim('not running')}`);console.log(` Home: ${chalk.dim(home)}`);console.log('');});+program+ .command('help')+ .description('Show capabilities and commands manual')+ .action(() => {+ console.log(getManual());+ });++const serviceCmd = program+ .command('service')+ .description('Manage Mercury as a system service (auto-start, crash recovery)');++serviceCmd+ .command('install')+ .description('Install Mercury as a system service (auto-start on boot)')+ .action(() => {+ installService();+ });++serviceCmd+ .command('uninstall')+ .description('Uninstall the system service')+ .action(() => {+ uninstallService();+ });++serviceCmd+ .command('status')+ .description('Show system service status')+ .action(() => {+ showServiceStatus();+ });+program.parse();\ No newline at end of filediff --git a/src/utils/manual.ts b/src/utils/manual.tsindex eb048d01..371c8eb1 100644--- a/src/utils/manual.ts+++ b/src/utils/manual.ts@@ -49,10 +49,17 @@ export function getManual(): string {const commands = [['mercury', 'Start the agent (same as mercury start)'],- ['mercury start', 'Start the agent'],+ ['mercury start', 'Start the agent in foreground'],+ ['mercury start -d', 'Start in background (daemon mode)'],+ ['mercury stop', 'Stop a background Mercury process'],+ ['mercury logs', 'Show recent daemon logs'],+ ['mercury doctor', 'Reconfigure settings (Enter keeps current)'],['mercury setup', 'Re-run the setup wizard'],- ['mercury status', 'Show current configuration'],+ ['mercury status', 'Show config and daemon status'],['mercury help', 'Show this manual'],+ ['mercury service install', 'Install as system service (auto-start)'],+ ['mercury service uninstall', 'Uninstall system service'],+ ['mercury service status', 'Show system service status'],['mercury --verbose', 'Start with debug logging on stderr'],];