Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
Add Telegram pairing and expand provider onboarding
M Shehzencbcac9b29adf
diff --git a/.env.example b/.env.exampleindex 33a060ee..dd39ac0c 100644--- a/.env.example+++ b/.env.example@@ -23,8 +23,23 @@ DEEPSEEK_API_KEY=DEEPSEEK_BASE_URL=https://api.deepseek.com/v1DEEPSEEK_MODEL=deepseek-chat-# Default provider: openai | anthropic | deepseek-DEFAULT_PROVIDER=openai+# Grok / xAI (OpenAI-compatible API)+GROK_API_KEY=+GROK_BASE_URL=https://api.x.ai/v1+GROK_MODEL=grok-4++# Ollama Cloud (API key required for ollama.com/api)+OLLAMA_CLOUD_API_KEY=+OLLAMA_CLOUD_BASE_URL=https://ollama.com/api+OLLAMA_CLOUD_MODEL=gpt-oss:120b++# Ollama Local (no API key required)+OLLAMA_LOCAL_BASE_URL=http://127.0.0.1:11434/api+OLLAMA_LOCAL_MODEL=gpt-oss:20b+OLLAMA_LOCAL_ENABLED=false++# Default provider: deepseek | openai | anthropic | grok | ollamaCloud | ollamaLocal+DEFAULT_PROVIDER=deepseek# ── Telegram ──# Get a bot token from @BotFather on Telegram@@ -37,4 +52,4 @@ MEMORY_DIR=./memoryHEARTBEAT_INTERVAL_MINUTES=60# ── Token Budget ──-DAILY_TOKEN_BUDGET=50000\ No newline at end of file+DAILY_TOKEN_BUDGET=50000diff --git a/README.md b/README.mdindex 3fb8f844..e8a8eda3 100644--- a/README.md+++ b/README.md@@ -181,6 +181,9 @@ Configure multiple LLM providers. Mercury tries them in order and falls back aut- **DeepSeek** — default, cost-effective- **OpenAI** — GPT-4o-mini and others- **Anthropic** — Claude and others+- **Grok / xAI** — OpenAI-compatible Grok models+- **Ollama Cloud** — remote Ollama models via API key+- **Ollama Local** — models running on your local Ollama instance## Architecturediff --git a/package-lock.json b/package-lock.jsonindex 6192cf43..322c1434 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{- "name": "mercury",- "version": "0.1.0",+ "name": "@cosmicstack/mercury-agent",+ "version": "0.2.4","lockfileVersion": 2,"requires": true,"packages": {"": {- "name": "mercury",- "version": "0.1.0",+ "name": "@cosmicstack/mercury-agent",+ "version": "0.2.4","license": "MIT","dependencies": {"@ai-sdk/anthropic": "^1.2.0",@@ -23,6 +23,7 @@"js-tiktoken": "^1.0.19","marked": "^14.1.4","node-cron": "^3.0.3",+ "ollama-ai-provider": "^1.2.0","pino": "^9.6.0","react": "^18.3.1","yaml": "^2.7.0",@@ -1976,6 +1977,28 @@"node": ">=0.10.0"}},+ "node_modules/ollama-ai-provider": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/ollama-ai-provider/-/ollama-ai-provider-1.2.0.tgz",+ "integrity": "sha512-jTNFruwe3O/ruJeppI/quoOUxG7NA6blG3ZyQj3lei4+NnJo7bi3eIRWqlVpRlu/mbzbFXeJSBuYQWF6pzGKww==",+ "license": "Apache-2.0",+ "dependencies": {+ "@ai-sdk/provider": "^1.0.0",+ "@ai-sdk/provider-utils": "^2.0.0",+ "partial-json": "0.1.7"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "zod": "^3.0.0"+ },+ "peerDependenciesMeta": {+ "zod": {+ "optional": true+ }+ }+ },"node_modules/on-exit-leak-free": {"version": "2.1.2","resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz",@@ -1998,6 +2021,12 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/partial-json": {+ "version": "0.1.7",+ "resolved": "https://registry.npmjs.org/partial-json/-/partial-json-0.1.7.tgz",+ "integrity": "sha512-Njv/59hHaokb/hRUjce3Hdv12wd60MtM9Z5Olmn+nehe0QDAsRtRbJPvJ0Z91TusF0SuZRIvnM+S4l6EIP8leA==",+ "license": "MIT"+ },"node_modules/patch-console": {"version": "2.0.0","resolved": "https://registry.npmjs.org/patch-console/-/patch-console-2.0.0.tgz",@@ -4627,6 +4656,16 @@"integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==","dev": true},+ "ollama-ai-provider": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/ollama-ai-provider/-/ollama-ai-provider-1.2.0.tgz",+ "integrity": "sha512-jTNFruwe3O/ruJeppI/quoOUxG7NA6blG3ZyQj3lei4+NnJo7bi3eIRWqlVpRlu/mbzbFXeJSBuYQWF6pzGKww==",+ "requires": {+ "@ai-sdk/provider": "^1.0.0",+ "@ai-sdk/provider-utils": "^2.0.0",+ "partial-json": "0.1.7"+ }+ },"on-exit-leak-free": {"version": "2.1.2","resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz",@@ -4640,6 +4679,11 @@"mimic-fn": "^2.1.0"}},+ "partial-json": {+ "version": "0.1.7",+ "resolved": "https://registry.npmjs.org/partial-json/-/partial-json-0.1.7.tgz",+ "integrity": "sha512-Njv/59hHaokb/hRUjce3Hdv12wd60MtM9Z5Olmn+nehe0QDAsRtRbJPvJ0Z91TusF0SuZRIvnM+S4l6EIP8leA=="+ },"patch-console": {"version": "2.0.0","resolved": "https://registry.npmjs.org/patch-console/-/patch-console-2.0.0.tgz",diff --git a/package.json b/package.jsonindex 06e1fde9..e8852da2 100644--- a/package.json+++ b/package.json@@ -68,6 +68,7 @@"js-tiktoken": "^1.0.19","marked": "^14.1.4","node-cron": "^3.0.3",+ "ollama-ai-provider": "^1.2.0","pino": "^9.6.0","react": "^18.3.1","yaml": "^2.7.0",@@ -84,4 +85,4 @@"engines": {"node": ">=20.0.0"}-}\ No newline at end of file+}diff --git a/src/channels/telegram.ts b/src/channels/telegram.tsindex 85da4d5e..e2efbe7c 100644--- a/src/channels/telegram.ts+++ b/src/channels/telegram.ts@@ -5,6 +5,7 @@ import { autoRetry } from '@grammyjs/auto-retry';import type { ChannelMessage } from '../types/channel.js';import { BaseChannel } from './base.js';import type { MercuryConfig } from '../utils/config.js';+import { saveConfig, clearTelegramPairing, setTelegramPairing } from '../utils/config.js';import { logger } from '../utils/logger.js';import { mdToTelegram } from '../utils/markdown.js';@@ -22,6 +23,7 @@ export class TelegramChannel extends BaseChannel {constructor(private config: MercuryConfig) {super();+ this.ownerChatId = config.channels.telegram.pairedChatId ?? null;}setChatCommandContext(ctx: import('../capabilities/registry.js').ChatCommandContext): void {@@ -40,11 +42,41 @@ export class TelegramChannel extends BaseChannel {bot.on('message:text', async (ctx) => {const chatId = ctx.chat.id;- if (!this.isAllowedChat(chatId)) return;+ const userId = ctx.from?.id;+ const text = ctx.message.text?.trim() || '';++ if (!userId) return;++ if (ctx.chat.type !== 'private') {+ await this.sendDirectMessage(chatId, 'This bot is only available in private one-to-one chats.');+ return;+ }++ if (!this.isPaired()) {+ await this.handleUnpairedMessage(userId, chatId, text, ctx.from?.username);+ return;+ }++ if (!this.isAuthorizedUser(userId)) {+ await this.sendDirectMessage(chatId, 'This bot is not available to you.');+ return;+ }this.ownerChatId = chatId;logger.info({ chatId, text: ctx.message.text?.slice(0, 50) }, 'Telegram message received');+ const command = text.toLowerCase();+ if (command === '/start' || command === '/pair') {+ await this.sendDirectMessage(chatId, this.getPairingStatusMessage());+ return;+ }++ if (command === '/unpair') {+ this.unpair();+ await this.sendDirectMessage(chatId, 'Telegram pairing removed. Send /start to pair this Mercury instance again.');+ return;+ }+const msg: ChannelMessage = {id: ctx.message.message_id.toString(),channelId: `telegram:${chatId}`,@@ -92,6 +124,8 @@ export class TelegramChannel extends BaseChannel {if (!this.bot) return;const commands = [+ { command: 'start', description: 'Pair this Telegram account to Mercury' },+ { command: 'pair', description: 'Pair this Telegram account to Mercury' },{ command: 'help', description: 'Show capabilities and commands manual' },{ command: 'status', description: 'Show agent config, budget, and uptime' },{ command: 'tools', description: 'List all loaded tools' },@@ -101,6 +135,7 @@ export class TelegramChannel extends BaseChannel {{ command: 'budget_reset', description: 'Reset token usage to zero' },{ command: 'budget_set', description: 'Set new daily token budget' },{ command: 'stream', description: 'Toggle text streaming on/off' },+ { command: 'unpair', description: 'Remove Telegram pairing for this Mercury instance' },];try {@@ -366,19 +401,62 @@ export class TelegramChannel extends BaseChannel {}private parseChatId(targetId?: string): number | null {- if (!targetId) return this.ownerChatId;+ if (!targetId) return this.ownerChatId ?? this.config.channels.telegram.pairedChatId ?? null;if (targetId.startsWith('telegram:')) {const raw = Number(targetId.split(':')[1]);- return isNaN(raw) ? this.ownerChatId : raw;+ return isNaN(raw) ? this.ownerChatId ?? this.config.channels.telegram.pairedChatId ?? null : raw;}- if (targetId === 'notification') return this.ownerChatId;+ if (targetId === 'notification') return this.ownerChatId ?? this.config.channels.telegram.pairedChatId ?? null;const num = Number(targetId);- return isNaN(num) ? this.ownerChatId : num;+ return isNaN(num) ? this.ownerChatId ?? this.config.channels.telegram.pairedChatId ?? null : num;+ }++ private isPaired(): boolean {+ return typeof this.config.channels.telegram.pairedUserId === 'number';+ }++ private isAuthorizedUser(userId: number): boolean {+ return this.config.channels.telegram.pairedUserId === userId;+ }++ private async handleUnpairedMessage(userId: number, chatId: number, text: string, username?: string): Promise<void> {+ const command = text.toLowerCase();+ if (command === '/start' || command === '/pair') {+ setTelegramPairing(this.config, userId, chatId, username);+ saveConfig(this.config);+ this.ownerChatId = chatId;+ logger.info({ chatId, userId, username }, 'Telegram paired to owner');+ await this.sendDirectMessage(chatId, this.getPairingStatusMessage(true));+ return;+ }++ await this.sendDirectMessage(+ chatId,+ 'This Mercury instance is not paired yet. Send /start to pair this bot to your Telegram account.',+ );}- private isAllowedChat(chatId: number): boolean {- const allowed = this.config.channels.telegram.allowedChatIds;- if (!allowed || allowed.length === 0) return true;- return allowed.includes(chatId);+ private getPairingStatusMessage(newlyPaired: boolean = false): string {+ const username = this.config.channels.telegram.pairedUsername+ ? ` (@${this.config.channels.telegram.pairedUsername})`+ : '';+ const prefix = newlyPaired ? 'Telegram paired successfully.' : 'This Telegram account is already paired.';+ return `${prefix}\n\nOwner user ID: ${this.config.channels.telegram.pairedUserId}${username}`;+ }++ private unpair(): void {+ clearTelegramPairing(this.config);+ saveConfig(this.config);+ this.ownerChatId = null;+ logger.info('Telegram pairing cleared');+ }++ private async sendDirectMessage(chatId: number, content: string): Promise<void> {+ if (!this.bot) return;+ try {+ await this.bot.api.sendMessage(chatId, mdToTelegram(content), { parse_mode: 'HTML' });+ } catch {+ await this.bot.api.sendMessage(chatId, content).catch(() => {});+ }}-}\ No newline at end of file+}diff --git a/src/core/agent.ts b/src/core/agent.tsindex fda03944..2c92179a 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -569,11 +569,15 @@ export class Agent {if (cmd === '/status') {const config = ctx.config();const budget = ctx.tokenBudget();+ const telegramPairing = config.channels.telegram.pairedUserId != null+ ? `paired to user ${config.channels.telegram.pairedUserId}${config.channels.telegram.pairedUsername ? ` (@${config.channels.telegram.pairedUsername})` : ''}`+ : 'unpaired';const lines = [`**${config.identity.name}** — Status`,`Owner: ${config.identity.owner || '(not set)'}`,`Provider: ${config.providers.default}`,`Telegram: ${config.channels.telegram.enabled ? 'enabled' : 'disabled'}`,+ `Telegram pairing: ${telegramPairing}`,`Budget: ${budget.getStatusText()}`,`Skills: ${ctx.skillNames().length > 0 ? ctx.skillNames().join(', ') : 'none'}`,];@@ -637,4 +641,4 @@ export class Agent {return false;}-}\ No newline at end of file+}diff --git a/src/index.ts b/src/index.tsindex 8828354d..77cf598a 100644--- a/src/index.ts+++ b/src/index.ts@@ -5,8 +5,9 @@ import { Command } from 'commander';import readline from 'node:readline';import chalk from 'chalk';import figlet from 'figlet';-import { loadConfig, saveConfig, isSetupComplete, getMercuryHome, ensureCreatorField } from './utils/config.js';+import { loadConfig, saveConfig, isSetupComplete, getMercuryHome, ensureCreatorField, clearTelegramPairing, isProviderConfigured } from './utils/config.js';import type { MercuryConfig } from './utils/config.js';+import type { ProviderName } from './utils/config.js';import { logger } from './utils/logger.js';import { Identity } from './soul/identity.js';import { ShortTermMemory, LongTermMemory, EpisodicMemory } from './memory/store.js';@@ -72,6 +73,193 @@ function maskKey(key: string): string {return key.slice(0, 4) + '••••' + key.slice(-4);}+const PROVIDER_OPTIONS: Array<{ key: ProviderName; label: string }> = [+ { key: 'deepseek', label: 'DeepSeek' },+ { key: 'openai', label: 'OpenAI' },+ { key: 'anthropic', label: 'Anthropic' },+ { key: 'grok', label: 'Grok (xAI)' },+ { key: 'ollamaCloud', label: 'Ollama Cloud' },+ { key: 'ollamaLocal', label: 'Ollama Local' },+];++function getConfiguredProviderNames(config: MercuryConfig): ProviderName[] {+ return PROVIDER_OPTIONS+ .map((option) => option.key)+ .filter((key) => isProviderConfigured(config.providers[key]));+}++function getProviderLabel(name: ProviderName): string {+ return PROVIDER_OPTIONS.find((option) => option.key === name)?.label || name;+}++function parseProviderSelection(input: string): ProviderName[] | null {+ const values = input.split(/[\s,]+/).map((value) => value.trim()).filter(Boolean);+ if (values.length === 0) return [];++ const selected: ProviderName[] = [];+ for (const value of values) {+ const index = parseInt(value, 10);+ if (isNaN(index) || index < 1 || index > PROVIDER_OPTIONS.length) {+ return null;+ }+ const provider = PROVIDER_OPTIONS[index - 1].key;+ if (!selected.includes(provider)) {+ selected.push(provider);+ }+ }+ return selected;+}++async function chooseProvidersToConfigure(config: MercuryConfig, isReconfig: boolean): Promise<ProviderName[]> {+ const configured = getConfiguredProviderNames(config);++ while (true) {+ for (let i = 0; i < PROVIDER_OPTIONS.length; i++) {+ const option = PROVIDER_OPTIONS[i];+ const status = configured.includes(option.key) ? ' (configured)' : '';+ console.log(chalk.white(` ${i + 1}. ${option.label}${status}`));+ }+ console.log('');++ const prompt = isReconfig+ ? chalk.white(' Choose providers to configure [comma-separated, Enter keeps current]: ')+ : chalk.white(' Choose providers to configure [comma-separated, Enter for DeepSeek]: ');++ const input = await ask(prompt);+ const parsed = parseProviderSelection(input);+ if (parsed === null) {+ console.log(chalk.red(' Please choose valid provider numbers, like `1` or `1,3,5`.'));+ console.log('');+ continue;+ }++ if (parsed.length > 0) return parsed;+ if (!isReconfig) return ['deepseek'];+ return configured.length > 0 ? configured : ['deepseek'];+ }+}++async function chooseDefaultProvider(config: MercuryConfig): Promise<void> {+ const configured = getConfiguredProviderNames(config);++ if (configured.length === 0) {+ console.log(chalk.red('\n At least one provider must be configured.'));+ process.exit(1);+ }++ if (configured.length === 1) {+ config.providers.default = configured[0];+ console.log(chalk.dim(` Default provider set to ${getProviderLabel(configured[0])}`));+ return;+ }++ const suggested = configured.includes('deepseek') ? 'deepseek' : configured[0];++ console.log('');+ console.log(chalk.bold.white(' Default Provider'));+ console.log(chalk.dim(' Select the LLM provider Mercury should use first.'));+ console.log('');+ for (let i = 0; i < configured.length; i++) {+ const provider = configured[i];+ const recommended = provider === suggested ? ' (recommended)' : '';+ const current = provider === config.providers.default ? ' (current)' : '';+ console.log(chalk.white(` ${i + 1}. ${getProviderLabel(provider)}${recommended}${current}`));+ }+ console.log('');++ while (true) {+ const choice = await ask(chalk.white(` Choose [1-${configured.length}] [Enter for ${getProviderLabel(suggested)}]: `));+ if (!choice) {+ config.providers.default = suggested;+ return;+ }++ const num = parseInt(choice, 10);+ if (num >= 1 && num <= configured.length) {+ config.providers.default = configured[num - 1];+ return;+ }++ console.log(chalk.red(' Please choose a valid number from the list above.'));+ }+}++function looksLikeToken(value: string, minLength: number = 20): boolean {+ return value.length >= minLength && !/\s/.test(value) && /[A-Za-z]/.test(value) && /\d/.test(value);+}++function validateApiKey(provider: ProviderName, value: string): string | null {+ if (provider === 'openai') {+ return /^sk-(proj-|svcacct-)?[A-Za-z0-9_-]{16,}$/i.test(value)+ ? null+ : 'OpenAI keys must start with `sk-`, `sk-proj-`, or `sk-svcacct-`.';+ }++ if (provider === 'anthropic') {+ return /^sk-ant-[A-Za-z0-9_-]{16,}$/i.test(value)+ ? null+ : 'Anthropic keys must start with `sk-ant-`.';+ }++ if (provider === 'deepseek') {+ return /^sk-[A-Za-z0-9_-]{16,}$/i.test(value)+ ? null+ : 'DeepSeek keys must start with `sk-`.';+ }++ if (provider === 'grok') {+ return looksLikeToken(value)+ ? null+ : 'Grok keys must look like a real API token: long, no spaces, and not plain text.';+ }++ if (provider === 'ollamaCloud') {+ return looksLikeToken(value)+ ? null+ : 'Ollama Cloud keys must look like a real API token: long, no spaces, and not plain text.';+ }++ return null;+}++function validateBaseUrl(value: string): string | null {+ try {+ const parsed = new URL(value);+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {+ return 'Base URL must start with http:// or https://.';+ }+ return null;+ } catch {+ return 'Please enter a valid URL.';+ }+}++function validateModelName(value: string): string | null {+ if (!value.trim()) return 'Model name is required.';+ if (/\s/.test(value)) return 'Model name cannot contain spaces.';+ return null;+}++async function promptValidatedValue(+ prompt: string,+ validator: (value: string) => string | null,+ existingValue?: string,+): Promise<string> {+ while (true) {+ const value = await ask(prompt);+ if (!value) {+ if (existingValue) return existingValue;+ console.log(chalk.red(' A value is required here.'));+ continue;+ }++ const error = validator(value);+ if (!error) return value;++ console.log(chalk.red(` ${error}`));+ }+}+async function configure(existingConfig?: MercuryConfig): Promise<void> {const isReconfig = !!existingConfig;const config = existingConfig ?? loadConfig();@@ -113,57 +301,90 @@ async function configure(existingConfig?: MercuryConfig): Promise<void> {console.log('');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.'));+ console.log(chalk.dim(' Choose which providers to configure now. Existing values are shown where available.'));} else {- console.log(chalk.dim(' At least one API key is required.'));+ console.log(chalk.dim(' Choose one or more providers. Press Enter to configure DeepSeek by default.'));}console.log('');- 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;- }+ const selectedProviders = await chooseProvidersToConfigure(config, isReconfig);+ console.log('');- 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;+ for (const provider of selectedProviders) {+ if (provider === 'deepseek') {+ const mask = isReconfig && config.providers.deepseek.apiKey ? ` [${maskKey(config.providers.deepseek.apiKey)}]` : '';+ config.providers.deepseek.apiKey = await promptValidatedValue(+ chalk.white(` DeepSeek API key${mask}: `),+ (value) => validateApiKey('deepseek', value),+ isReconfig ? config.providers.deepseek.apiKey : undefined,+ );+ config.providers.deepseek.enabled = true;+ continue;+ }- 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 (provider === 'openai') {+ const mask = isReconfig && config.providers.openai.apiKey ? ` [${maskKey(config.providers.openai.apiKey)}]` : '';+ config.providers.openai.apiKey = await promptValidatedValue(+ chalk.white(` OpenAI API key${mask}: `),+ (value) => validateApiKey('openai', value),+ isReconfig ? config.providers.openai.apiKey : undefined,+ );+ config.providers.openai.enabled = true;+ continue;+ }- 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);- }+ if (provider === 'anthropic') {+ const mask = isReconfig && config.providers.anthropic.apiKey ? ` [${maskKey(config.providers.anthropic.apiKey)}]` : '';+ config.providers.anthropic.apiKey = await promptValidatedValue(+ chalk.white(` Anthropic API key${mask}: `),+ (value) => validateApiKey('anthropic', value),+ isReconfig ? config.providers.anthropic.apiKey : undefined,+ );+ config.providers.anthropic.enabled = true;+ continue;+ }- const availableProviders: string[] = [];- if (config.providers.deepseek.apiKey) availableProviders.push('deepseek');- if (config.providers.openai.apiKey) availableProviders.push('openai');- if (config.providers.anthropic.apiKey) availableProviders.push('anthropic');+ if (provider === 'grok') {+ const mask = isReconfig && config.providers.grok.apiKey ? ` [${maskKey(config.providers.grok.apiKey)}]` : '';+ config.providers.grok.apiKey = await promptValidatedValue(+ chalk.white(` Grok API key${mask}: `),+ (value) => validateApiKey('grok', value),+ isReconfig ? config.providers.grok.apiKey : undefined,+ );+ config.providers.grok.enabled = true;+ continue;+ }- if (isReconfig && availableProviders.length > 1) {- console.log('');- console.log(chalk.bold.white(' Default Provider'));- console.log(chalk.dim(' Select the default LLM provider (the one used first).'));- console.log('');- for (let i = 0; i < availableProviders.length; i++) {- const marker = availableProviders[i] === config.providers.default ? ' (current)' : '';- console.log(chalk.white(` ${i + 1}. ${availableProviders[i]}${marker}`));+ if (provider === 'ollamaCloud') {+ const mask = isReconfig && config.providers.ollamaCloud.apiKey ? ` [${maskKey(config.providers.ollamaCloud.apiKey)}]` : '';+ config.providers.ollamaCloud.apiKey = await promptValidatedValue(+ chalk.white(` Ollama Cloud API key${mask}: `),+ (value) => validateApiKey('ollamaCloud', value),+ isReconfig ? config.providers.ollamaCloud.apiKey : undefined,+ );+ config.providers.ollamaCloud.enabled = true;+ continue;}- console.log('');- const choice = await ask(chalk.white(` Choose [1-${availableProviders.length}] [Enter to keep ${config.providers.default}]: `));- const num = parseInt(choice, 10);- if (num >= 1 && num <= availableProviders.length) {- config.providers.default = availableProviders[num - 1];++ if (provider === 'ollamaLocal') {+ config.providers.ollamaLocal.baseUrl = await promptValidatedValue(+ chalk.white(` Ollama Local base URL [${config.providers.ollamaLocal.baseUrl}]: `),+ validateBaseUrl,+ config.providers.ollamaLocal.baseUrl,+ );++ config.providers.ollamaLocal.model = await promptValidatedValue(+ chalk.white(` Ollama Local model [${config.providers.ollamaLocal.model}]: `),+ validateModelName,+ config.providers.ollamaLocal.model,+ );++ config.providers.ollamaLocal.enabled = true;}- } else if (!isReconfig) {- config.providers.default = availableProviders[0];- console.log(chalk.dim(` Default provider set to ${config.providers.default}`));}+ await chooseDefaultProvider(config);+hr();console.log('');console.log(chalk.bold.white(' Telegram (optional)'));@@ -179,7 +400,11 @@ async function configure(existingConfig?: MercuryConfig): Promise<void> {if (isReconfig && telegramToken.toLowerCase() === 'none') {config.channels.telegram.enabled = false;config.channels.telegram.botToken = '';+ clearTelegramPairing(config);} else if (telegramToken) {+ if (telegramToken !== config.channels.telegram.botToken) {+ clearTelegramPairing(config);+ }config.channels.telegram.botToken = telegramToken;config.channels.telegram.enabled = true;}@@ -262,10 +487,10 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {if (!providers.hasProviders()) {if (isDaemon) {- logger.error('No LLM providers available. Run `mercury doctor` to configure API keys.');+ logger.error('No LLM providers available. Run `mercury doctor` to configure providers.');return;}- console.log(chalk.red(' No LLM providers available. Run `mercury doctor` to configure API keys.'));+ console.log(chalk.red(' No LLM providers available. Run `mercury doctor` to configure providers.'));process.exit(1);}@@ -493,8 +718,9 @@ programif (config.identity.creator) {console.log(` Creator: ${chalk.white(config.identity.creator)}`);}- console.log(` Provider: ${chalk.white(config.providers.default)}`);+ console.log(` Provider: ${chalk.white(getProviderLabel(config.providers.default))}`);console.log(` Telegram: ${config.channels.telegram.enabled ? chalk.green('enabled') : chalk.dim('disabled')}`);+ console.log(` Telegram Pairing: ${config.channels.telegram.pairedUserId != null ? chalk.green(`paired to user ${config.channels.telegram.pairedUserId}${config.channels.telegram.pairedUsername ? ` (@${config.channels.telegram.pairedUsername})` : ''}`) : chalk.dim('unpaired')}`);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.toLocaleString())} tokens/day`);console.log(` Setup: ${isSetupComplete() ? chalk.green('complete') : chalk.red('not done')}`);@@ -510,6 +736,37 @@ programconsole.log(getManual());});+const telegramCmd = program+ .command('telegram')+ .description('Manage Telegram pairing and access');++telegramCmd+ .command('unpair')+ .description('Clear the paired Telegram owner for this Mercury instance')+ .action(() => {+ const config = loadConfig();+ const daemon = getDaemonStatus();+ if (config.channels.telegram.pairedUserId == null) {+ console.log('');+ console.log(chalk.dim(' Telegram is already unpaired.'));+ console.log('');+ return;+ }++ clearTelegramPairing(config);+ saveConfig(config);++ console.log('');+ console.log(chalk.green(' ✓ Telegram pairing cleared.'));+ if (daemon.running) {+ console.log(chalk.dim(' Restarting the background daemon to apply the change immediately...'));+ restartDaemon();+ } else {+ console.log(chalk.dim(' The next private Telegram user to send /start will pair this Mercury instance.'));+ }+ console.log('');+ });+const serviceCmd = program.command('service').description('Manage Mercury as a system service (auto-start, crash recovery)');@@ -535,4 +792,4 @@ serviceCmdshowServiceStatus();});-program.parse();\ No newline at end of file+program.parse();diff --git a/src/providers/index.ts b/src/providers/index.tsindex 9edb71c0..140df082 100644--- a/src/providers/index.ts+++ b/src/providers/index.ts@@ -1,5 +1,6 @@export { BaseProvider } from './base.js';export { OpenAICompatProvider } from './openai-compat.js';export { AnthropicProvider } from './anthropic.js';+export { OllamaProvider } from './ollama.js';export { ProviderRegistry } from './registry.js';-export type { LLMResponse, LLMStreamChunk } from './base.js';\ No newline at end of file+export type { LLMResponse, LLMStreamChunk } from './base.js';diff --git a/src/providers/ollama.ts b/src/providers/ollama.tsnew file mode 100644index 00000000..0b024dff--- /dev/null+++ b/src/providers/ollama.ts@@ -0,0 +1,46 @@+import { createOllama } from 'ollama-ai-provider';+import { BaseProvider } from './base.js';+import type { ProviderConfig } from '../utils/config.js';++export class OllamaProvider extends BaseProvider {+ readonly name: string;+ readonly model: string;+ private client: ReturnType<typeof createOllama>;+ private modelInstance: any;++ constructor(config: ProviderConfig) {+ super(config);+ this.name = config.name;+ this.model = config.model;++ const headers = config.apiKey+ ? { Authorization: `Bearer ${config.apiKey}` }+ : undefined;++ this.client = createOllama({+ baseURL: config.baseUrl,+ headers,+ });+ this.modelInstance = this.client(config.model);+ }++ async generateText(_prompt: string, _systemPrompt: string): Promise<never> {+ throw new Error('Use getModelInstance() with the AI SDK agent loop');+ }++ async *streamText(_prompt: string, _systemPrompt: string): AsyncIterable<never> {+ throw new Error('Use getModelInstance() with the AI SDK agent loop');+ }++ isAvailable(): boolean {+ if (!this.config.enabled) return false;+ if (this.name === 'ollamaLocal') {+ return this.config.baseUrl.length > 0 && this.config.model.length > 0;+ }+ return this.config.apiKey.length > 0;+ }++ getModelInstance() {+ return this.modelInstance;+ }+}diff --git a/src/providers/registry.ts b/src/providers/registry.tsindex e0b3f212..d6f3e104 100644--- a/src/providers/registry.ts+++ b/src/providers/registry.ts@@ -1,7 +1,9 @@import type { MercuryConfig, ProviderConfig } from '../utils/config.js';+import { isProviderConfigured } from '../utils/config.js';import type { BaseProvider } from './base.js';import { OpenAICompatProvider } from './openai-compat.js';import { AnthropicProvider } from './anthropic.js';+import { OllamaProvider } from './ollama.js';import { logger } from '../utils/logger.js';export class ProviderRegistry {@@ -13,17 +15,25 @@ export class ProviderRegistry {this.defaultName = config.providers.default;const entries: ProviderConfig[] = [+ config.providers.deepseek,config.providers.openai,config.providers.anthropic,- config.providers.deepseek,+ config.providers.grok,+ config.providers.ollamaCloud,+ config.providers.ollamaLocal,];for (const pc of entries) {- if (!pc.enabled || !pc.apiKey) continue;+ if (!isProviderConfigured(pc)) continue;try {- const provider = pc.name === 'anthropic'- ? new AnthropicProvider(pc)- : new OpenAICompatProvider(pc);+ let provider: BaseProvider;+ if (pc.name === 'anthropic') {+ provider = new AnthropicProvider(pc);+ } else if (pc.name === 'ollamaCloud' || pc.name === 'ollamaLocal') {+ provider = new OllamaProvider(pc);+ } else {+ provider = new OpenAICompatProvider(pc);+ }this.providers.set(pc.name, provider);logger.info({ provider: pc.name, model: pc.model }, 'Provider registered');} catch (err) {@@ -75,4 +85,4 @@ export class ProviderRegistry {hasProviders(): boolean {return this.providers.size > 0;}-}\ No newline at end of file+}diff --git a/src/types/channel.ts b/src/types/channel.tsindex 33108392..d587953b 100644--- a/src/types/channel.ts+++ b/src/types/channel.ts@@ -22,8 +22,12 @@ export interface TelegramChannelConfig extends ChannelConfig {botToken: string;webhookUrl?: string;allowedChatIds?: number[];+ streaming?: boolean;+ pairedUserId?: number;+ pairedChatId?: number;+ pairedUsername?: string;}export interface CLIChannelConfig extends ChannelConfig {type: 'cli';-}\ No newline at end of file+}diff --git a/src/utils/config.ts b/src/utils/config.tsindex 16a5af40..22d2b5e6 100644--- a/src/utils/config.ts+++ b/src/utils/config.ts@@ -20,6 +20,14 @@ export interface ProviderConfig {enabled: boolean;}+export type ProviderName =+ | 'openai'+ | 'anthropic'+ | 'deepseek'+ | 'grok'+ | 'ollamaCloud'+ | 'ollamaLocal';+export interface MercuryConfig {identity: {name: string;@@ -27,10 +35,13 @@ export interface MercuryConfig {creator?: string;};providers: {- default: string;+ default: ProviderName;openai: ProviderConfig;anthropic: ProviderConfig;deepseek: ProviderConfig;+ grok: ProviderConfig;+ ollamaCloud: ProviderConfig;+ ollamaLocal: ProviderConfig;};channels: {telegram: {@@ -39,6 +50,9 @@ export interface MercuryConfig {webhookUrl?: string;allowedChatIds?: number[];streaming?: boolean;+ pairedUserId?: number;+ pairedChatId?: number;+ pairedUsername?: string;};};memory: {@@ -78,7 +92,7 @@ export function getDefaultConfig(): MercuryConfig {creator: getEnv('MERCURY_CREATOR', ''),},providers: {- default: getEnv('DEFAULT_PROVIDER', 'openai'),+ default: getEnv('DEFAULT_PROVIDER', 'deepseek') as ProviderName,openai: {name: 'openai',apiKey: getEnv('OPENAI_API_KEY', ''),@@ -100,6 +114,27 @@ export function getDefaultConfig(): MercuryConfig {model: getEnv('DEEPSEEK_MODEL', 'deepseek-chat'),enabled: getEnvBool('DEEPSEEK_ENABLED', true),},+ grok: {+ name: 'grok',+ apiKey: getEnv('GROK_API_KEY', ''),+ baseUrl: getEnv('GROK_BASE_URL', 'https://api.x.ai/v1'),+ model: getEnv('GROK_MODEL', 'grok-4'),+ enabled: getEnvBool('GROK_ENABLED', true),+ },+ ollamaCloud: {+ name: 'ollamaCloud',+ apiKey: getEnv('OLLAMA_CLOUD_API_KEY', ''),+ baseUrl: getEnv('OLLAMA_CLOUD_BASE_URL', 'https://ollama.com/api'),+ model: getEnv('OLLAMA_CLOUD_MODEL', 'gpt-oss:120b'),+ enabled: getEnvBool('OLLAMA_CLOUD_ENABLED', true),+ },+ ollamaLocal: {+ name: 'ollamaLocal',+ apiKey: '',+ baseUrl: getEnv('OLLAMA_LOCAL_BASE_URL', 'http://127.0.0.1:11434/api'),+ model: getEnv('OLLAMA_LOCAL_MODEL', 'gpt-oss:20b'),+ enabled: getEnvBool('OLLAMA_LOCAL_ENABLED', false),+ },},channels: {telegram: {@@ -184,5 +219,27 @@ function deepMerge<T extends Record<string, any>>(target: T, source: Partial<T>)export function getActiveProviders(config: MercuryConfig): ProviderConfig[] {return Object.values(config.providers)- .filter((p): p is ProviderConfig => typeof p === 'object' && p.enabled && p.apiKey.length > 0);-}\ No newline at end of file+ .filter((p): p is ProviderConfig => typeof p === 'object' && isProviderConfigured(p));+}++export function isProviderConfigured(provider: ProviderConfig): boolean {+ if (!provider.enabled) return false;+ if (provider.name === 'ollamaLocal') {+ return provider.baseUrl.length > 0 && provider.model.length > 0;+ }+ return provider.apiKey.length > 0;+}++export function setTelegramPairing(config: MercuryConfig, userId: number, chatId: number, username?: string): MercuryConfig {+ config.channels.telegram.pairedUserId = userId;+ config.channels.telegram.pairedChatId = chatId;+ config.channels.telegram.pairedUsername = username || undefined;+ return config;+}++export function clearTelegramPairing(config: MercuryConfig): MercuryConfig {+ delete config.channels.telegram.pairedUserId;+ delete config.channels.telegram.pairedChatId;+ delete config.channels.telegram.pairedUsername;+ return config;+}diff --git a/src/utils/manual.ts b/src/utils/manual.tsindex b370ad6a..8a7d7790 100644--- a/src/utils/manual.ts+++ b/src/utils/manual.ts@@ -58,6 +58,7 @@ export function getManual(): string {['mercury doctor', 'Reconfigure settings (Enter keeps current)'],['mercury setup', 'Re-run the setup wizard'],['mercury status', 'Show config and daemon status'],+ ['mercury telegram unpair', 'Clear the paired Telegram owner'],['mercury help', 'Show this manual'],['mercury service install', 'Install as system service (auto-start)'],['mercury service uninstall', 'Uninstall system service'],@@ -75,6 +76,8 @@ export function getManual(): string {sections.push('');const chat = [+ ['/start', 'Pair this Telegram account to Mercury'],+ ['/pair', 'Pair this Telegram account to Mercury'],['/help', 'Show this manual'],['/status', 'Show config and budget info'],['/tools', 'List currently loaded tools'],@@ -82,6 +85,7 @@ export function getManual(): string {['/stream', 'Toggle text streaming on/off (Telegram)'],['/stream on', 'Enable streaming (live text updates)'],['/stream off', 'Disable streaming (single message)'],+ ['/unpair', 'Remove Telegram pairing for this Mercury instance'],];for (const [cmd, desc] of chat) {@@ -155,4 +159,4 @@ export function getManual(): string {sections.push('');return sections.join('\n');-}\ No newline at end of file+}