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.

refactor: migrate configuration and data storage to user home directory and enhance CLI/Telegram channel UX

Salman Qureshi3d0c72a8d0e2
diff --git a/.gitignore b/.gitignore
index c5dfafbd..7df34dba 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,8 +2,8 @@ node_modules/
dist/
.env
*.log
-memory/short-term/
-memory/long-term/
-memory/episodic/
.DS_Store
-*.tsbuildinfo
\ No newline at end of file
+*.tsbuildinfo
+config/
+memory/
+soul/
\ No newline at end of file
diff --git a/skills/_template/index.ts b/skills/_template/index.ts
deleted file mode 100644
index dbb0696e..00000000
--- a/skills/_template/index.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import type { Skill, SkillInput, SkillOutput } from '../../src/skills/types.js';
-
-export default {
- manifest: {
- name: 'template-skill',
- version: '0.1.0',
- description: 'A template skill for Mercury',
- triggers: ['template'],
- capabilities: ['example'],
- },
- async execute(input: SkillInput): Promise<SkillOutput> {
- return {
- response: `Template skill executed with: ${input.message}`,
- success: true,
- };
- },
-} satisfies Skill;
\ No newline at end of file
diff --git a/skills/_template/manifest.json b/skills/_template/manifest.json
deleted file mode 100644
index e4ecfb8d..00000000
--- a/skills/_template/manifest.json
+++ /dev/null
@@ -1,7 +0,0 @@
-{
- "name": "template-skill",
- "version": "0.1.0",
- "description": "A template skill for Mercury",
- "triggers": ["template"],
- "capabilities": ["example"]
-}
\ No newline at end of file
diff --git a/skills/_template/skill.md b/skills/_template/skill.md
deleted file mode 100644
index 137c5de7..00000000
--- a/skills/_template/skill.md
+++ /dev/null
@@ -1,12 +0,0 @@
-# Template Skill
-
-This is a template skill for Mercury.
-
-## What It Does
-Describe what this skill enables Mercury to do.
-
-## Triggers
-List the keywords or patterns that activate this skill.
-
-## Usage
-Describe how the owner invokes this skill.
\ No newline at end of file
diff --git a/src/channels/cli.ts b/src/channels/cli.ts
index 7fbbb9aa..add3f842 100644
--- a/src/channels/cli.ts
+++ b/src/channels/cli.ts
@@ -1,4 +1,5 @@
import readline from 'node:readline';
+import chalk from 'chalk';
import type { ChannelMessage } from '../types/channel.js';
import { BaseChannel } from './base.js';
import { logger } from '../utils/logger.js';
@@ -6,11 +7,22 @@ import { logger } from '../utils/logger.js';
export class CLIChannel extends BaseChannel {
readonly type = 'cli' as const;
private rl: readline.Interface | null = null;
+ private agentName: string;
+
+ constructor(agentName: string = 'Mercury') {
+ super();
+ this.agentName = agentName;
+ }
+
+ setAgentName(name: string): void {
+ this.agentName = name;
+ }
async start(): Promise<void> {
this.rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
+ prompt: '',
});
this.rl.on('line', (line) => {
@@ -39,18 +51,27 @@ export class CLIChannel extends BaseChannel {
}
async send(content: string, _targetId?: string): Promise<void> {
- process.stdout.write(content + '\n');
+ console.log('');
+ console.log(chalk.cyan(` ${this.agentName}: `) + content);
+ console.log('');
+ this.showPrompt();
}
async stream(content: AsyncIterable<string>, _targetId?: string): Promise<void> {
+ process.stdout.write(chalk.cyan(` ${this.agentName}: `));
for await (const chunk of content) {
process.stdout.write(chunk);
}
- process.stdout.write('\n');
+ process.stdout.write('\n\n');
+ this.showPrompt();
}
async typing(_targetId?: string): Promise<void> {
- process.stdout.write('...');
+ process.stdout.write(chalk.dim(` ${this.agentName} is thinking...\r`));
+ }
+
+ showPrompt(): void {
+ process.stdout.write(' You: ');
}
async prompt(question: string): Promise<string> {
diff --git a/src/channels/registry.ts b/src/channels/registry.ts
index 746731b1..f89ac0bd 100644
--- a/src/channels/registry.ts
+++ b/src/channels/registry.ts
@@ -9,7 +9,7 @@ export class ChannelRegistry {
private channels: Map<ChannelType, Channel> = new Map();
constructor(config: MercuryConfig) {
- this.register('cli', new CLIChannel());
+ this.register('cli', new CLIChannel(config.identity.name));
if (config.channels.telegram.enabled && config.channels.telegram.botToken) {
this.register('telegram', new TelegramChannel(config));
diff --git a/src/channels/telegram.ts b/src/channels/telegram.ts
index 7cb9f091..8bb4a86b 100644
--- a/src/channels/telegram.ts
+++ b/src/channels/telegram.ts
@@ -1,4 +1,4 @@
-import { Bot, type Context } from 'grammy';
+import { Bot } from 'grammy';
import { autoRetry } from '@grammyjs/auto-retry';
import type { ChannelMessage } from '../types/channel.js';
import { BaseChannel } from './base.js';
@@ -30,6 +30,7 @@ export class TelegramChannel extends BaseChannel {
if (!this.isAllowedChat(chatId)) return;
this.ownerChatId = chatId;
+ logger.info({ chatId, text: ctx.message.text?.slice(0, 50) }, 'Telegram message received');
const msg: ChannelMessage = {
id: ctx.message.message_id.toString(),
@@ -44,11 +45,15 @@ export class TelegramChannel extends BaseChannel {
this.emit(msg);
});
+ bot.catch((err) => {
+ logger.error({ err: err.message }, 'Telegram bot error');
+ });
+
this.bot = bot;
await bot.start({
onStart: (info) => {
- logger.info({ bot: info.username }, 'Telegram bot started');
+ logger.info({ bot: info.username }, 'Telegram bot started — long polling active');
this.ready = true;
},
});
@@ -61,13 +66,17 @@ export class TelegramChannel extends BaseChannel {
}
async send(content: string, targetId?: string): Promise<void> {
- const chatId = targetId ? Number(targetId) : this.ownerChatId;
- if (!chatId || !this.bot) return;
+ const chatId = this.parseChatId(targetId);
+ if (!chatId || !this.bot) {
+ logger.warn({ targetId, chatId }, 'Telegram send: no valid chat ID');
+ return;
+ }
+ logger.debug({ chatId, textLen: content.length }, 'Telegram sending message');
await this.bot.api.sendMessage(chatId, content);
}
async stream(content: AsyncIterable<string>, targetId?: string): Promise<void> {
- const chatId = targetId ? Number(targetId) : this.ownerChatId;
+ const chatId = this.parseChatId(targetId);
if (!chatId || !this.bot) return;
let full = '';
@@ -78,7 +87,7 @@ export class TelegramChannel extends BaseChannel {
}
async typing(targetId?: string): Promise<void> {
- const chatId = targetId ? Number(targetId) : this.ownerChatId;
+ const chatId = this.parseChatId(targetId);
if (!chatId || !this.bot) return;
await this.bot.api.sendChatAction(chatId, 'typing');
}
@@ -112,6 +121,16 @@ export class TelegramChannel extends BaseChannel {
}
}
+ private parseChatId(targetId?: string): number | null {
+ if (!targetId) return this.ownerChatId;
+ if (targetId.startsWith('telegram:')) {
+ const raw = Number(targetId.split(':')[1]);
+ return isNaN(raw) ? this.ownerChatId : raw;
+ }
+ const num = Number(targetId);
+ return isNaN(num) ? this.ownerChatId : num;
+ }
+
private isAllowedChat(chatId: number): boolean {
const allowed = this.config.channels.telegram.allowedChatIds;
if (!allowed || allowed.length === 0) return true;
diff --git a/src/core/agent.ts b/src/core/agent.ts
index 77700dae..b52363fd 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -13,6 +13,8 @@ export class Agent {
readonly lifecycle: Lifecycle;
readonly scheduler: Scheduler;
private running = false;
+ private messageQueue: ChannelMessage[] = [];
+ private processing = false;
constructor(
private config: MercuryConfig,
@@ -27,13 +29,38 @@ export class Agent {
this.lifecycle = new Lifecycle();
this.scheduler = new Scheduler(config);
- this.channels.onIncomingMessage((msg) => this.handleMessage(msg));
+ this.channels.onIncomingMessage((msg) => this.enqueueMessage(msg));
this.scheduler.onHeartbeat(async () => {
await this.heartbeat();
});
}
+ private enqueueMessage(msg: ChannelMessage): void {
+ logger.info({ from: msg.channelType, content: msg.content.slice(0, 50) }, 'Message enqueued');
+ this.messageQueue.push(msg);
+ this.processQueue();
+ }
+
+ private async processQueue(): Promise<void> {
+ if (this.processing) return;
+ if (this.messageQueue.length === 0) return;
+ if (!this.lifecycle.is('idle')) return;
+
+ this.processing = true;
+
+ while (this.messageQueue.length > 0) {
+ const msg = this.messageQueue.shift()!;
+ try {
+ await this.handleMessage(msg);
+ } catch (err) {
+ logger.error({ err, msg: msg.content.slice(0, 50) }, 'Failed to handle message');
+ }
+ }
+
+ this.processing = false;
+ }
+
async birth(): Promise<void> {
this.lifecycle.transition('birthing');
logger.info({ name: this.config.identity.name }, 'Mercury is being born...');
@@ -59,12 +86,7 @@ export class Agent {
logger.info('Mercury is sleeping');
}
- async handleMessage(msg: ChannelMessage): Promise<void> {
- if (!this.lifecycle.is('idle')) {
- logger.debug({ state: this.lifecycle.getState() }, 'Message received but not idle');
- return;
- }
-
+ private async handleMessage(msg: ChannelMessage): Promise<void> {
this.lifecycle.transition('thinking');
try {
@@ -72,7 +94,6 @@ export class Agent {
const systemPrompt = this.identity.getSystemPrompt(this.config.identity);
const recentMemory = this.shortTerm.getRecent(msg.channelId, 10);
const relevantFacts = this.longTerm.search(msg.content, 3);
- const recentEvents = this.episodic.getRecent(5);
let contextPrompt = '';
if (relevantFacts.length > 0) {
@@ -90,10 +111,12 @@ export class Agent {
const channel = this.channels.getChannelForMessage(msg);
if (channel) {
- await channel.typing(msg.channelId);
+ await channel.typing(msg.channelId).catch(() => {});
}
+ logger.info({ provider: provider.name, model: provider.getModel() }, 'Generating response');
const response = await provider.generateText(fullPrompt, systemPrompt);
+ logger.info({ tokens: response.totalTokens }, 'Response generated');
this.tokenBudget.recordUsage({
provider: response.provider,
@@ -126,7 +149,10 @@ export class Agent {
});
if (channel) {
+ logger.info({ channelType: msg.channelType, targetId: msg.channelId }, 'Sending response');
await channel.send(response.text, msg.channelId);
+ } else {
+ logger.warn({ channelType: msg.channelType }, 'No channel found for response');
}
this.lifecycle.transition('idle');
diff --git a/src/index.ts b/src/index.ts
index 69003f19..2b3d85d9 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -1,121 +1,214 @@
-#!/usr/bin/env node
-
import { Command } from 'commander';
-import { loadConfig, saveConfig } from './utils/config.js';
+import readline from 'node:readline';
+import chalk from 'chalk';
+import { loadConfig, saveConfig, isSetupComplete, getMercuryHome } from './utils/config.js';
import { logger } from './utils/logger.js';
import { Identity } from './soul/identity.js';
import { ShortTermMemory, LongTermMemory, EpisodicMemory } from './memory/store.js';
import { ProviderRegistry } from './providers/registry.js';
-import { ChannelRegistry } from './channels/registry.js';
import { Agent } from './core/agent.js';
+import { ChannelRegistry } from './channels/registry.js';
+import { CLIChannel } from './channels/cli.js';
import { TokenBudget } from './utils/tokens.js';
import { SkillLoader } from './skills/loader.js';
+function hr() {
+ console.log(chalk.dim('─'.repeat(50)));
+}
+
+function banner() {
+ console.log('');
+ console.log(chalk.cyan(' ╦═╗┌─┐┌┬┐┬┬ ┬┌─┐'));
+ console.log(chalk.cyan(' ╠╦╝├┤ │ ││ │├┤ '));
+ console.log(chalk.cyan(' ╩╚═└─┘ ┴ ┴┴─┘└─┘'));
+ console.log(chalk.dim(' v0.1.0 — an AI agent for personal tasks'));
+ console.log('');
+}
+
+async function ask(prompt: string): Promise<string> {
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
+ return new Promise((resolve) => {
+ rl.question(prompt, (answer) => {
+ rl.close();
+ resolve(answer.trim());
+ });
+ });
+}
+
+async function onboarding(): Promise<void> {
+ banner();
+ console.log(chalk.yellow(' First run detected — let\'s set you up.'));
+ hr();
+ console.log('');
+
+ const config = loadConfig();
+
+ 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 agentName = await ask(chalk.white(` Agent name [${config.identity.name}]: `));
+ if (agentName) config.identity.name = agentName;
+
+ hr();
+ console.log('');
+ console.log(chalk.white(' LLM Providers'));
+ console.log(chalk.dim(' At least one API key is required.'));
+ console.log('');
+
+ const deepseekKey = await ask(chalk.white(' DeepSeek API key: '));
+ if (deepseekKey) {
+ config.providers.deepseek.apiKey = deepseekKey;
+ config.providers.default = 'deepseek';
+ }
+
+ const openaiKey = await ask(chalk.white(' OpenAI API key (Enter to skip): '));
+ if (openaiKey) config.providers.openai.apiKey = openaiKey;
+
+ const anthropicKey = await ask(chalk.white(' Anthropic API key (Enter to skip): '));
+ if (anthropicKey) config.providers.anthropic.apiKey = anthropicKey;
+
+ if (!deepseekKey && !openaiKey && !anthropicKey) {
+ 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('');
+
+ const telegramToken = await ask(chalk.white(' Telegram Bot Token: '));
+ if (telegramToken) {
+ config.channels.telegram.botToken = telegramToken;
+ config.channels.telegram.enabled = true;
+ }
+
+ hr();
+ saveConfig(config);
+
+ const home = getMercuryHome();
+ console.log('');
+ console.log(chalk.green(` ✓ Config saved to ${home}/mercury.yaml`));
+ console.log(chalk.green(` ✓ Soul files will be seeded in ${home}/soul/`));
+ console.log(chalk.green(` ✓ Memory stored in ${home}/memory/`));
+ console.log('');
+ console.log(chalk.cyan(` ${config.identity.name} is ready. Run \`mercury start\` to begin.`));
+ console.log('');
+}
+
+async function runAgent(): Promise<void> {
+ const config = loadConfig();
+ const name = config.identity.name;
+
+ banner();
+ console.log(chalk.white(` ${name} is waking up...`));
+ console.log('');
+
+ 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.'));
+ process.exit(1);
+ }
+
+ const available = providers.listAvailable();
+ console.log(chalk.dim(` Providers: ${available.join(', ')}`));
+
+ const identity = new Identity();
+ const shortTerm = new ShortTermMemory(config);
+ const longTerm = new LongTermMemory(config);
+ const episodic = new EpisodicMemory(config);
+ const skillLoader = new SkillLoader();
+ const skills = skillLoader.discover();
+ if (skills.length > 0) {
+ console.log(chalk.dim(` Skills: ${skills.map(s => s.name).join(', ')}`));
+ }
+
+ const channels = new ChannelRegistry(config);
+
+ const agent = new Agent(
+ config, providers, identity, shortTerm, longTerm, episodic, channels, tokenBudget,
+ );
+
+ await agent.birth();
+ await agent.wake();
+
+ const cliChannel = channels.get('cli') as CLIChannel | undefined;
+
+ const activeCh = channels.getActiveChannels();
+ console.log(chalk.dim(` Channels: ${activeCh.join(', ')}`));
+ 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('');
+
+ cliChannel?.showPrompt();
+
+ const shutdown = async () => {
+ console.log('');
+ console.log(chalk.dim(` ${name} is shutting down...`));
+ await agent.shutdown();
+ process.exit(0);
+ };
+
+ process.on('SIGINT', shutdown);
+ process.on('SIGTERM', shutdown);
+}
+
const program = new Command();
program
.name('mercury')
.description('Mercury — an AI agent for personal tasks')
- .version('0.1.0');
+ .version('0.1.0')
+ .action(async () => {
+ if (!isSetupComplete()) {
+ await onboarding();
+ return;
+ }
+ await runAgent();
+ });
program
.command('start')
.description('Start Mercury agent')
- .option('-m, --mode <mode>', 'Run mode: cli, daemon', 'cli')
- .action(async (opts) => {
- const config = loadConfig();
-
- if (!config.identity.owner) {
- logger.error('Owner not set. Run `mercury setup` first.');
- process.exit(1);
- }
-
- const tokenBudget = new TokenBudget(config);
- const providers = new ProviderRegistry(config);
-
- if (!providers.hasProviders()) {
- logger.error('No LLM providers available. Set API keys in .env or mercury.yaml.');
- process.exit(1);
+ .action(async () => {
+ if (!isSetupComplete()) {
+ await onboarding();
+ return;
}
-
- const identity = new Identity(config);
- const shortTerm = new ShortTermMemory(config);
- const longTerm = new LongTermMemory(config);
- const episodic = new EpisodicMemory(config);
- const skillLoader = new SkillLoader();
- const discoveredSkills = skillLoader.discover();
-
- logger.info({ skills: discoveredSkills.map(s => s.name) }, 'Skills loaded');
-
- const channels = new ChannelRegistry(config);
- const agent = new Agent(
- config, providers, identity, shortTerm, longTerm, episodic, channels, tokenBudget,
- );
-
- await agent.birth();
- await agent.wake();
-
- const shutdown = async () => {
- await agent.shutdown();
- process.exit(0);
- };
-
- process.on('SIGINT', shutdown);
- process.on('SIGTERM', shutdown);
+ await runAgent();
});
program
.command('setup')
- .description('Configure Mercury (interactive setup)')
+ .description('Re-run the setup wizard')
.action(async () => {
- const config = loadConfig();
-
- const readline = await import('node:readline/promises');
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
-
- console.log(`\n Mercury Setup Wizard\n ${'─'.repeat(30)}\n`);
-
- const ownerName = await rl.question(' Your name: ');
- config.identity.owner = ownerName || config.identity.owner;
-
- const agentName = await rl.question(` Agent name [${config.identity.name}]: `);
- if (agentName) config.identity.name = agentName;
-
- console.log('\n LLM Providers\n');
-
- const openaiKey = await rl.question(' OpenAI API key: ');
- if (openaiKey) config.providers.openai.apiKey = openaiKey;
-
- const anthropicKey = await rl.question(' Anthropic API key (optional): ');
- if (anthropicKey) config.providers.anthropic.apiKey = anthropicKey;
-
- const deepseekKey = await rl.question(' DeepSeek API key (optional): ');
- if (deepseekKey) config.providers.deepseek.apiKey = deepseekKey;
-
- console.log('\n Telegram (optional)\n');
-
- const telegramToken = await rl.question(' Telegram Bot Token (leave empty to skip): ');
- if (telegramToken) {
- config.channels.telegram.botToken = telegramToken;
- config.channels.telegram.enabled = true;
- }
-
- saveConfig(config);
- console.log(`\n Configuration saved.\n Run \`mercury start\` to begin.\n`);
-
- rl.close();
+ await onboarding();
});
program
.command('status')
- .description('Show Mercury status')
+ .description('Show current configuration')
.action(() => {
const config = loadConfig();
- console.log(` Name: ${config.identity.name}`);
- console.log(` Owner: ${config.identity.owner || '(not set)'}`);
- console.log(` Default: ${config.providers.default}`);
- console.log(` Telegram: ${config.channels.telegram.enabled ? 'enabled' : 'disabled'}`);
- console.log(` Budget: ${config.tokens.dailyBudget} tokens/day`);
+ const home = getMercuryHome();
+ banner();
+ console.log(` Name: ${chalk.cyan(config.identity.name)}`);
+ console.log(` Owner: ${chalk.white(config.identity.owner || '(not set)')}`);
+ console.log(` Provider: ${chalk.white(config.providers.default)}`);
+ console.log(` Telegram: ${config.channels.telegram.enabled ? chalk.green('enabled') : chalk.dim('disabled')}`);
+ 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)}`);
+ console.log('');
});
program.parse();
\ No newline at end of file
diff --git a/src/skills/loader.ts b/src/skills/loader.ts
index 59a0634f..404cddf1 100644
--- a/src/skills/loader.ts
+++ b/src/skills/loader.ts
@@ -1,5 +1,6 @@
-import { existsSync, readFileSync, readdirSync } from 'node:fs';
+import { existsSync, readFileSync, readdirSync, mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
+import { getMercuryHome } from '../utils/config.js';
import type { SkillManifest } from './types.js';
import { logger } from '../utils/logger.js';
@@ -8,12 +9,16 @@ export class SkillLoader {
private manifests: Map<string, SkillManifest> = new Map();
constructor(skillsDir?: string) {
- this.skillsDir = skillsDir || join(process.cwd(), 'skills');
+ this.skillsDir = skillsDir || join(getMercuryHome(), 'skills');
}
discover(): SkillManifest[] {
this.manifests.clear();
- if (!existsSync(this.skillsDir)) return [];
+ if (!existsSync(this.skillsDir)) {
+ mkdirSync(this.skillsDir, { recursive: true });
+ this.seedTemplate();
+ return [];
+ }
const entries = readdirSync(this.skillsDir, { withFileTypes: true });
for (const entry of entries) {
@@ -40,4 +45,31 @@ export class SkillLoader {
getAllManifests(): SkillManifest[] {
return [...this.manifests.values()];
}
+
+ 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'
+ );
+
+ logger.info('Seeded template skill');
+ }
}
\ No newline at end of file
diff --git a/src/soul/identity.ts b/src/soul/identity.ts
index 96b00e91..b061df27 100644
--- a/src/soul/identity.ts
+++ b/src/soul/identity.ts
@@ -1,6 +1,6 @@
import { existsSync, readFileSync, mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
-import type { MercuryConfig } from '../utils/config.js';
+import { getMercuryHome } from '../utils/config.js';
import { logger } from '../utils/logger.js';
export interface SoulFiles {
@@ -92,8 +92,8 @@ export class Identity {
private soulDir: string;
private cache: SoulFiles | null = null;
- constructor(config: MercuryConfig) {
- this.soulDir = join(process.cwd(), 'soul');
+ constructor() {
+ this.soulDir = join(getMercuryHome(), 'soul');
}
load(): SoulFiles {
diff --git a/src/utils/config.ts b/src/utils/config.ts
index b57ed51c..81063167 100644
--- a/src/utils/config.ts
+++ b/src/utils/config.ts
@@ -1,10 +1,17 @@
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
import { join } from 'node:path';
+import { homedir } from 'node:os';
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
import { config as loadDotenv } from 'dotenv';
loadDotenv();
+const MERCURY_HOME = join(homedir(), '.mercury');
+
+export function getMercuryHome(): string {
+ return process.env.MERCURY_HOME || MERCURY_HOME;
+}
+
export interface ProviderConfig {
name: string;
apiKey: string;
@@ -44,8 +51,6 @@ export interface MercuryConfig {
};
}
-const CONFIG_PATH = join(process.cwd(), 'config', 'mercury.yaml');
-
function getEnv(key: string, fallback: string = ''): string {
return process.env[key] || fallback;
}
@@ -63,6 +68,7 @@ function getEnvBool(key: string, fallback: boolean): boolean {
}
export function getDefaultConfig(): MercuryConfig {
+ const home = getMercuryHome();
return {
identity: {
name: getEnv('MERCURY_NAME', 'Mercury'),
@@ -104,7 +110,7 @@ export function getDefaultConfig(): MercuryConfig {
},
},
memory: {
- dir: getEnv('MEMORY_DIR', join(process.cwd(), 'memory')),
+ dir: getEnv('MEMORY_DIR', join(home, 'memory')),
shortTermMaxMessages: getEnvNum('SHORT_TERM_MAX_MESSAGES', 20),
},
heartbeat: {
@@ -116,6 +122,8 @@ export function getDefaultConfig(): MercuryConfig {
};
}
+const CONFIG_PATH = join(getMercuryHome(), 'mercury.yaml');
+
export function loadConfig(): MercuryConfig {
if (existsSync(CONFIG_PATH)) {
const raw = readFileSync(CONFIG_PATH, 'utf-8');
@@ -127,13 +135,19 @@ export function loadConfig(): MercuryConfig {
}
export function saveConfig(config: MercuryConfig): void {
- const dir = join(process.cwd(), 'config');
+ const dir = getMercuryHome();
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true });
}
writeFileSync(CONFIG_PATH, stringifyYaml(config), 'utf-8');
}
+export function isSetupComplete(): boolean {
+ if (!existsSync(CONFIG_PATH)) return false;
+ const config = loadConfig();
+ return config.identity.owner.length > 0;
+}
+
function deepMerge<T extends Record<string, any>>(target: T, source: Partial<T>): T {
const result = { ...target };
for (const key in source) {