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.

Add Telegram access management and CLI command menus

M Shehzenef8101ceab5a
diff --git a/src/capabilities/filesystem/send-file.ts b/src/capabilities/filesystem/send-file.ts
index c6e89424..ba2ca1a6 100644
--- a/src/capabilities/filesystem/send-file.ts
+++ b/src/capabilities/filesystem/send-file.ts
@@ -10,7 +10,7 @@ export function createSendFileTool(
) {
return tool({
description:
- 'Send a file to the user. On Telegram the file is uploaded as an attachment. On CLI the file path and size are displayed. The path must be within an allowed read scope.',
+ 'Send a file to the user. On Telegram the file is uploaded as an attachment to the relevant approved recipients. On CLI the file path and size are displayed. The path must be within an allowed read scope.',
parameters: z.object({
path: z.string().describe('Absolute or relative path to the file to send'),
}),
@@ -48,4 +48,4 @@ export function createSendFileTool(
}
},
});
-}
\ No newline at end of file
+}
diff --git a/src/capabilities/messaging/send-message.ts b/src/capabilities/messaging/send-message.ts
index 6ee79c46..8cfdbb9b 100644
--- a/src/capabilities/messaging/send-message.ts
+++ b/src/capabilities/messaging/send-message.ts
@@ -6,9 +6,9 @@ export function createSendMessageTool(
) {
return tool({
description:
- 'Send a message to the paired user through the configured outbound channel. Currently this sends only to the paired Telegram owner. Use this only when the user explicitly asks you to send something to Telegram or asks for scheduled results to be sent there.',
+ 'Send a message through the configured outbound channel. For Telegram this sends to the approved Telegram recipients. Use this only when the user explicitly asks you to send something to Telegram or asks for scheduled results to be sent there.',
parameters: z.object({
- content: z.string().describe('The message content to send to the paired Telegram owner'),
+ content: z.string().describe('The message content to send to the approved Telegram recipients'),
}),
execute: async ({ content }) => {
const trimmed = content.trim();
@@ -18,7 +18,7 @@ export function createSendMessageTool(
try {
await sendMessage(trimmed);
- return 'Message sent to the paired Telegram owner.';
+ return 'Message sent to the approved Telegram recipients.';
} catch (err: any) {
return `Error sending message: ${err.message}`;
}
diff --git a/src/channels/cli.ts b/src/channels/cli.ts
index aa888a7f..c453cdde 100644
--- a/src/channels/cli.ts
+++ b/src/channels/cli.ts
@@ -6,11 +6,13 @@ import type { ChannelMessage } from '../types/channel.js';
import { BaseChannel } from './base.js';
import { logger } from '../utils/logger.js';
import { renderMarkdown } from '../utils/markdown.js';
+import { selectWithArrowKeys, type ArrowSelectOption } from '../utils/arrow-select.js';
export class CLIChannel extends BaseChannel {
readonly type = 'cli' as const;
private rl: readline.Interface | null = null;
private agentName: string;
+ private menuDepth = 0;
constructor(agentName: string = 'Mercury') {
super();
@@ -22,6 +24,13 @@ export class CLIChannel extends BaseChannel {
}
async start(): Promise<void> {
+ this.createInterface();
+ this.ready = true;
+ this.showPrompt();
+ logger.info('CLI channel started');
+ }
+
+ private createInterface(): void {
this.rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
@@ -45,10 +54,6 @@ export class CLIChannel extends BaseChannel {
};
this.emit(msg);
});
-
- this.ready = true;
- this.showPrompt();
- logger.info('CLI channel started');
}
async stop(): Promise<void> {
@@ -68,7 +73,9 @@ export class CLIChannel extends BaseChannel {
.join('\n');
console.log(indented);
console.log('');
- this.showPrompt();
+ if (this.menuDepth === 0) {
+ this.showPrompt();
+ }
}
async sendFile(filePath: string, _targetId?: string): Promise<void> {
@@ -88,7 +95,9 @@ export class CLIChannel extends BaseChannel {
console.log(chalk.dim(` path: ${resolved}`));
console.log(chalk.dim(` size: ${sizeStr}`));
console.log('');
- this.showPrompt();
+ if (this.menuDepth === 0) {
+ this.showPrompt();
+ }
}
async stream(content: AsyncIterable<string>, _targetId?: string): Promise<string> {
@@ -100,7 +109,9 @@ export class CLIChannel extends BaseChannel {
full += chunk;
}
console.log('\n');
- this.showPrompt();
+ if (this.menuDepth === 0) {
+ this.showPrompt();
+ }
return full;
}
@@ -115,6 +126,33 @@ export class CLIChannel extends BaseChannel {
}
}
+ async withMenu<T>(runner: (select: (title: string, options: ArrowSelectOption[]) => Promise<string>) => Promise<T>): Promise<T> {
+ this.menuDepth += 1;
+ this.suspendPrompt();
+
+ try {
+ return await runner((title, options) => selectWithArrowKeys(title, options));
+ } finally {
+ this.menuDepth = Math.max(0, this.menuDepth - 1);
+ if (this.menuDepth === 0) {
+ this.resumePrompt();
+ this.showPrompt();
+ }
+ }
+ }
+
+ private suspendPrompt(): void {
+ if (!this.rl) return;
+ process.stdout.write('\n');
+ this.rl.close();
+ this.rl = null;
+ }
+
+ private resumePrompt(): void {
+ if (!this.ready || this.rl) return;
+ this.createInterface();
+ }
+
async prompt(question: string): Promise<string> {
return new Promise((resolve) => {
this.rl?.question(question, (answer) => resolve(answer.trim()));
@@ -130,4 +168,4 @@ export class CLIChannel extends BaseChannel {
});
});
}
-}
\ No newline at end of file
+}
diff --git a/src/channels/telegram.ts b/src/channels/telegram.ts
index e2efbe7c..0ed195c1 100644
--- a/src/channels/telegram.ts
+++ b/src/channels/telegram.ts
@@ -4,26 +4,39 @@ import { Bot, InputFile, InlineKeyboard } from 'grammy';
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 type { MercuryConfig, TelegramAccessUser, TelegramPendingRequest } from '../utils/config.js';
+import {
+ addTelegramPendingRequest,
+ approveTelegramPendingRequest,
+ clearTelegramAccess,
+ findTelegramAdmin,
+ findTelegramApprovedUser,
+ findTelegramPendingRequest,
+ getTelegramAccessSummary,
+ getTelegramAdmins,
+ getTelegramApprovedChatIds,
+ hasTelegramAdmins,
+ rejectTelegramPendingRequest,
+ saveConfig,
+} from '../utils/config.js';
import { logger } from '../utils/logger.js';
import { mdToTelegram } from '../utils/markdown.js';
const MAX_MESSAGE_LENGTH = 4096;
+const ACCESS_ACTION_PREFIX = 'tg_access';
type ApprovalResolver = (response: 'yes' | 'always' | 'no') => void;
export class TelegramChannel extends BaseChannel {
readonly type = 'telegram' as const;
private bot: Bot | null = null;
- private ownerChatId: number | null = null;
+ private lastActiveChatId: number | null = null;
private typingInterval: NodeJS.Timeout | null = null;
private chatCommandContext?: import('../capabilities/registry.js').ChatCommandContext;
private pendingApprovals: Map<string, ApprovalResolver> = new Map();
constructor(private config: MercuryConfig) {
super();
- this.ownerChatId = config.channels.telegram.pairedChatId ?? null;
}
setChatCommandContext(ctx: import('../capabilities/registry.js').ChatCommandContext): void {
@@ -43,7 +56,10 @@ export class TelegramChannel extends BaseChannel {
bot.on('message:text', async (ctx) => {
const chatId = ctx.chat.id;
const userId = ctx.from?.id;
+ const username = ctx.from?.username;
+ const firstName = ctx.from?.first_name;
const text = ctx.message.text?.trim() || '';
+ const command = this.getCommandName(text);
if (!userId) return;
@@ -52,28 +68,36 @@ export class TelegramChannel extends BaseChannel {
return;
}
- if (!this.isPaired()) {
- await this.handleUnpairedMessage(userId, chatId, text, ctx.from?.username);
+ if (command === '/start' || command === '/pair') {
+ await this.handleAccessRequest(userId, chatId, username, firstName);
return;
}
- if (!this.isAuthorizedUser(userId)) {
- await this.sendDirectMessage(chatId, 'This bot is not available to you.');
+ const approvedUser = findTelegramApprovedUser(this.config, userId);
+ if (!approvedUser) {
+ const pending = findTelegramPendingRequest(this.config, userId);
+ if (pending) {
+ await this.sendDirectMessage(chatId, this.getPendingStatusMessage());
+ } else {
+ await this.sendDirectMessage(chatId, 'This bot is not available to you. Send /start to request access.');
+ }
return;
}
- this.ownerChatId = chatId;
+ this.lastActiveChatId = 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.');
+ if (!this.isAdminUser(userId)) {
+ await this.sendDirectMessage(chatId, 'Only Telegram admins can reset Telegram access.');
+ return;
+ }
+
+ this.resetAccess();
+ await this.sendDirectMessage(
+ chatId,
+ 'Telegram access reset. New users can send /start to request access. The first request must be approved from the Mercury CLI.',
+ );
return;
}
@@ -92,6 +116,11 @@ export class TelegramChannel extends BaseChannel {
bot.on('callback_query:data', async (ctx) => {
const data = ctx.callbackQuery.data;
+ if (data.startsWith(`${ACCESS_ACTION_PREFIX}:`)) {
+ await this.handleAccessCallback(ctx, data);
+ return;
+ }
+
const resolver = this.pendingApprovals.get(data);
if (!resolver) {
await ctx.answerCallbackQuery({ text: 'Expired' });
@@ -111,12 +140,27 @@ export class TelegramChannel extends BaseChannel {
this.bot = bot;
- await bot.start({
- onStart: async (info) => {
- logger.info({ bot: info.username }, 'Telegram bot started — long polling active');
- this.ready = true;
- await this.registerCommands();
- },
+ await new Promise<void>((resolve, reject) => {
+ let settled = false;
+
+ void bot.start({
+ onStart: async (info) => {
+ logger.info({ bot: info.username }, 'Telegram bot started — long polling active');
+ this.ready = true;
+ await this.registerCommands();
+ if (!settled) {
+ settled = true;
+ resolve();
+ }
+ },
+ }).catch((err: any) => {
+ if (!settled) {
+ settled = true;
+ reject(err);
+ return;
+ }
+ logger.error({ err: err.message }, 'Telegram bot start loop failed after startup');
+ });
});
}
@@ -124,8 +168,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: 'start', description: 'Request Telegram access to this Mercury instance' },
+ { command: 'pair', description: 'Request Telegram access to this Mercury instance' },
{ command: 'help', description: 'Show capabilities and commands manual' },
{ command: 'status', description: 'Show agent config, budget, and uptime' },
{ command: 'tools', description: 'List all loaded tools' },
@@ -135,7 +179,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' },
+ { command: 'unpair', description: 'Reset all Telegram access for this Mercury instance' },
];
try {
@@ -153,84 +197,95 @@ export class TelegramChannel extends BaseChannel {
}
async send(content: string, targetId?: string, elapsedMs?: number): Promise<void> {
- const chatId = this.parseChatId(targetId);
- if (!chatId || !this.bot) {
- logger.warn({ targetId, chatId }, 'Telegram send: no valid chat ID');
+ const chatIds = this.resolveTargetChatIds(targetId);
+ if (chatIds.length === 0 || !this.bot) {
+ logger.warn({ targetId, chatIds }, 'Telegram send: no valid chat IDs');
return;
}
+
const timeSuffix = elapsedMs != null ? `\n⏱ ${(elapsedMs / 1000).toFixed(1)}s` : '';
const fullContent = content + timeSuffix;
const html = mdToTelegram(fullContent);
const chunks = this.splitMessage(html, MAX_MESSAGE_LENGTH);
- for (const chunk of chunks) {
- try {
- await this.bot.api.sendMessage(chatId, chunk, { parse_mode: 'HTML' });
- } catch (err: any) {
- logger.warn({ err: err.message }, 'HTML parse failed, sending as plain text');
+ for (const chatId of chatIds) {
+ for (const chunk of chunks) {
try {
- await this.bot.api.sendMessage(chatId, this.stripHtml(chunk));
- } catch (err2: any) {
- logger.error({ err: err2.message }, 'Telegram send failed');
+ await this.bot.api.sendMessage(chatId, chunk, { parse_mode: 'HTML' });
+ } catch (err: any) {
+ logger.warn({ err: err.message, chatId }, 'HTML parse failed, sending as plain text');
+ try {
+ await this.bot.api.sendMessage(chatId, this.stripHtml(chunk));
+ } catch (err2: any) {
+ logger.error({ err: err2.message, chatId }, 'Telegram send failed');
+ }
}
}
}
}
async sendFile(filePath: string, targetId?: string): Promise<void> {
- const chatId = this.parseChatId(targetId);
- if (!chatId || !this.bot) {
- logger.warn({ targetId, chatId }, 'Telegram sendFile: no valid chat ID');
+ const chatIds = this.resolveTargetChatIds(targetId);
+ if (chatIds.length === 0 || !this.bot) {
+ logger.warn({ targetId, chatIds }, 'Telegram sendFile: no valid chat IDs');
return;
}
+
const resolved = path.resolve(filePath);
if (!fs.existsSync(resolved)) {
- await this.bot.api.sendMessage(chatId, `File not found: ${filePath}`);
+ for (const chatId of chatIds) {
+ await this.bot.api.sendMessage(chatId, `File not found: ${filePath}`).catch(() => {});
+ }
return;
}
- const inputFile = new InputFile(resolved);
const filename = path.basename(resolved);
const ext = path.extname(resolved).toLowerCase();
- try {
- if (this.isImageFile(ext)) {
- await this.bot.api.sendPhoto(chatId, inputFile, { caption: filename });
- } else if (this.isAudioFile(ext)) {
- await this.bot.api.sendAudio(chatId, inputFile, { title: filename });
- } else if (this.isVideoFile(ext)) {
- await this.bot.api.sendVideo(chatId, inputFile, { caption: filename });
- } else {
- await this.bot.api.sendDocument(chatId, inputFile, { caption: filename });
+ for (const chatId of chatIds) {
+ const inputFile = new InputFile(resolved);
+
+ try {
+ if (this.isImageFile(ext)) {
+ await this.bot.api.sendPhoto(chatId, inputFile, { caption: filename });
+ } else if (this.isAudioFile(ext)) {
+ await this.bot.api.sendAudio(chatId, inputFile, { title: filename });
+ } else if (this.isVideoFile(ext)) {
+ await this.bot.api.sendVideo(chatId, inputFile, { caption: filename });
+ } else {
+ await this.bot.api.sendDocument(chatId, inputFile, { caption: filename });
+ }
+ logger.info({ file: resolved, chatId }, 'File sent via Telegram');
+ } catch (err: any) {
+ logger.error({ err: err.message, file: resolved, chatId }, 'Telegram sendFile failed');
+ await this.bot.api.sendMessage(chatId, `Failed to send file: ${err.message}`).catch(() => {});
}
- logger.info({ file: resolved, chatId }, 'File sent via Telegram');
- } catch (err: any) {
- logger.error({ err: err.message, file: resolved }, 'Telegram sendFile failed');
- await this.bot.api.sendMessage(chatId, `Failed to send file: ${err.message}`).catch(() => {});
}
}
async stream(content: AsyncIterable<string>, targetId?: string): Promise<string> {
- const chatId = this.parseChatId(targetId);
- if (!chatId || !this.bot) return '';
+ const chatIds = this.resolveTargetChatIds(targetId);
+ if (chatIds.length === 0 || !this.bot) return '';
let full = '';
for await (const chunk of content) {
full += chunk;
}
const html = mdToTelegram(full);
- try {
- await this.bot.api.sendMessage(chatId, html, { parse_mode: 'HTML' });
- } catch (err: any) {
- await this.bot.api.sendMessage(chatId, this.stripHtml(html));
+ for (const chatId of chatIds) {
+ try {
+ await this.bot.api.sendMessage(chatId, html, { parse_mode: 'HTML' });
+ } catch (err: any) {
+ await this.bot.api.sendMessage(chatId, this.stripHtml(html)).catch(() => {});
+ }
}
return full;
}
async typing(targetId?: string): Promise<void> {
- const chatId = this.parseChatId(targetId);
- if (!chatId || !this.bot) return;
- await this.bot.api.sendChatAction(chatId, 'typing');
+ const chatIds = this.resolveTargetChatIds(targetId);
+ if (chatIds.length === 0 || !this.bot) return;
+ await this.bot.api.sendChatAction(chatIds[0], 'typing');
}
startTypingLoop(chatId: number): void {
@@ -316,7 +371,8 @@ export class TelegramChannel extends BaseChannel {
}
async askPermission(prompt: string, targetId?: string): Promise<string> {
- const chatId = this.parseChatId(targetId);
+ const chatIds = this.resolveTargetChatIds(targetId);
+ const chatId = chatIds[0];
if (!chatId || !this.bot) return 'no';
const id = `perm_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
@@ -352,6 +408,208 @@ export class TelegramChannel extends BaseChannel {
});
}
+ private async handleAccessRequest(
+ userId: number,
+ chatId: number,
+ username?: string,
+ firstName?: string,
+ ): Promise<void> {
+ const approvedUser = findTelegramApprovedUser(this.config, userId);
+ if (approvedUser) {
+ await this.sendDirectMessage(chatId, this.getApprovedStatusMessage(approvedUser));
+ return;
+ }
+
+ const existingRequest = findTelegramPendingRequest(this.config, userId);
+ if (existingRequest) {
+ await this.sendDirectMessage(chatId, this.getPendingStatusMessage(existingRequest));
+ return;
+ }
+
+ if (!hasTelegramAdmins(this.config) && this.config.channels.telegram.pending.length > 0) {
+ await this.sendDirectMessage(
+ chatId,
+ 'Initial Telegram pairing is already in progress for another user. Ask the Mercury operator to finish setup or reset Telegram access first.',
+ );
+ return;
+ }
+
+ const request = addTelegramPendingRequest(this.config, {
+ userId,
+ chatId,
+ username,
+ firstName,
+ pairingCode: hasTelegramAdmins(this.config) ? undefined : this.generatePairingCode(),
+ });
+ saveConfig(this.config);
+ logger.info({ chatId, userId, username }, 'Telegram access request recorded');
+
+ await this.sendDirectMessage(chatId, this.getPendingStatusMessage(request));
+
+ if (!hasTelegramAdmins(this.config)) {
+ return;
+ }
+
+ await this.notifyAdminsOfPendingRequest(request);
+ }
+
+ private async notifyAdminsOfPendingRequest(request: TelegramPendingRequest): Promise<void> {
+ if (!this.bot) return;
+
+ const keyboard = new InlineKeyboard()
+ .text('Approve', `${ACCESS_ACTION_PREFIX}:approve:${request.userId}`)
+ .text('Reject', `${ACCESS_ACTION_PREFIX}:reject:${request.userId}`);
+
+ const username = request.username ? ` (@${request.username})` : '';
+ const firstName = request.firstName ? ` (${request.firstName})` : '';
+ const message = [
+ 'Telegram access request pending approval.',
+ '',
+ `User ID: ${request.userId}${username}${firstName}`,
+ `Requested: ${new Date(request.requestedAt).toLocaleString()}`,
+ '',
+ 'Use the buttons below to approve or reject this user.',
+ ].join('\n');
+
+ for (const admin of getTelegramAdmins(this.config)) {
+ try {
+ await this.bot.api.sendMessage(admin.chatId, mdToTelegram(message), {
+ parse_mode: 'HTML',
+ reply_markup: keyboard,
+ });
+ } catch {
+ await this.bot.api.sendMessage(admin.chatId, message, {
+ reply_markup: keyboard,
+ }).catch(() => {});
+ }
+ }
+ }
+
+ private async handleAccessCallback(ctx: Parameters<Bot['on']>[1] extends never ? never : any, data: string): Promise<void> {
+ const actorUserId = ctx.from?.id;
+ const actorChatId = ctx.chat?.id;
+ if (!actorUserId || !actorChatId) {
+ await ctx.answerCallbackQuery({ text: 'Unavailable' });
+ return;
+ }
+
+ if (!this.isAdminUser(actorUserId)) {
+ await ctx.answerCallbackQuery({ text: 'Admins only' });
+ return;
+ }
+
+ const [, action, rawUserId] = data.split(':');
+ const requestUserId = Number(rawUserId);
+ if (!requestUserId) {
+ await ctx.answerCallbackQuery({ text: 'Invalid request' });
+ return;
+ }
+
+ const request = findTelegramPendingRequest(this.config, requestUserId);
+ if (!request) {
+ await ctx.answerCallbackQuery({ text: 'Already handled' });
+ await ctx.editMessageReplyMarkup({ reply_markup: undefined }).catch(() => {});
+ return;
+ }
+
+ if (action === 'approve') {
+ const approved = approveTelegramPendingRequest(this.config, requestUserId, 'member');
+ if (!approved) {
+ await ctx.answerCallbackQuery({ text: 'Already handled' });
+ return;
+ }
+
+ saveConfig(this.config);
+ await ctx.answerCallbackQuery({ text: 'Approved' });
+ await ctx.editMessageReplyMarkup({ reply_markup: undefined }).catch(() => {});
+ await this.sendDirectMessage(
+ request.chatId,
+ `Telegram access approved. You can now chat with Mercury.\n\nTelegram access: ${getTelegramAccessSummary(this.config)}`,
+ );
+ await this.sendDirectMessage(actorChatId, `Approved Telegram access for ${this.formatRequestLabel(request)}.`);
+ return;
+ }
+
+ if (action === 'reject') {
+ const rejected = rejectTelegramPendingRequest(this.config, requestUserId);
+ if (!rejected) {
+ await ctx.answerCallbackQuery({ text: 'Already handled' });
+ return;
+ }
+
+ saveConfig(this.config);
+ await ctx.answerCallbackQuery({ text: 'Rejected' });
+ await ctx.editMessageReplyMarkup({ reply_markup: undefined }).catch(() => {});
+ await this.sendDirectMessage(
+ request.chatId,
+ 'Your Telegram access request was rejected. This bot is not available to you.',
+ );
+ await this.sendDirectMessage(actorChatId, `Rejected Telegram access for ${this.formatRequestLabel(request)}.`);
+ return;
+ }
+
+ await ctx.answerCallbackQuery({ text: 'Unknown action' });
+ }
+
+ private resolveTargetChatIds(targetId?: string): number[] {
+ if (!targetId || targetId === 'notification') {
+ return getTelegramApprovedChatIds(this.config);
+ }
+
+ if (targetId.startsWith('telegram:')) {
+ const raw = Number(targetId.split(':')[1]);
+ return isNaN(raw) ? [] : [raw];
+ }
+
+ const num = Number(targetId);
+ return isNaN(num) ? [] : [num];
+ }
+
+ private isAdminUser(userId: number): boolean {
+ return !!findTelegramAdmin(this.config, userId);
+ }
+
+ private getCommandName(text: string): string {
+ return text.trim().split(/\s+/)[0]?.toLowerCase() || '';
+ }
+
+ private getPendingStatusMessage(request?: TelegramPendingRequest): string {
+ if (!hasTelegramAdmins(this.config)) {
+ const pairingCode = request?.pairingCode ?? 'unknown';
+ return [
+ 'Your Telegram pairing request has been recorded.',
+ '',
+ `Pairing code: ${pairingCode}`,
+ '',
+ 'Enter this code in the Mercury terminal to finish setup.',
+ ].join('\n');
+ }
+
+ return 'Your Telegram access request has been recorded and is waiting for approval from a Telegram admin.';
+ }
+
+ private getApprovedStatusMessage(user: TelegramAccessUser): string {
+ const role = this.isAdminUser(user.userId) ? 'admin' : 'member';
+ return `You are already approved as a Telegram ${role}.\n\nTelegram access: ${getTelegramAccessSummary(this.config)}`;
+ }
+
+ private formatRequestLabel(request: TelegramPendingRequest): string {
+ const username = request.username ? ` (@${request.username})` : '';
+ const firstName = request.firstName ? ` ${request.firstName}` : '';
+ return `${request.userId}${username}${firstName}`;
+ }
+
+ private resetAccess(): void {
+ clearTelegramAccess(this.config);
+ saveConfig(this.config);
+ this.lastActiveChatId = null;
+ logger.info('Telegram access reset');
+ }
+
+ private generatePairingCode(): string {
+ return Math.floor(100000 + Math.random() * 900000).toString();
+ }
+
private escapeHtml(text: string): string {
return text
.replace(/&/g, '&amp;')
@@ -400,57 +658,6 @@ export class TelegramChannel extends BaseChannel {
return ['.mp4', '.mov', '.avi', '.mkv', '.webm'].includes(ext);
}
- private parseChatId(targetId?: string): number | null {
- 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 ?? this.config.channels.telegram.pairedChatId ?? null : raw;
- }
- if (targetId === 'notification') return this.ownerChatId ?? this.config.channels.telegram.pairedChatId ?? null;
- const num = Number(targetId);
- 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 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 {
diff --git a/src/core/agent.ts b/src/core/agent.ts
index 08a37be2..f2116b80 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -11,6 +11,21 @@ import type { ScheduledTaskManifest } from './scheduler.js';
import { Lifecycle } from './lifecycle.js';
import { Scheduler } from './scheduler.js';
import { logger } from '../utils/logger.js';
+import { CLIChannel } from '../channels/cli.js';
+import type { ArrowSelectOption } from '../utils/arrow-select.js';
+import {
+ approveTelegramPendingRequest,
+ approveTelegramPendingRequestByPairingCode,
+ clearTelegramAccess,
+ demoteTelegramAdmin,
+ getTelegramAccessSummary,
+ getTelegramApprovedUsers,
+ getTelegramPendingRequests,
+ promoteTelegramUserToAdmin,
+ rejectTelegramPendingRequest,
+ removeTelegramUser,
+ saveConfig,
+} from '../utils/config.js';
const MAX_STEPS = 10;
@@ -566,7 +581,8 @@ export class Agent {
}
private async handleChatCommand(content: string, channelType: string, channelId: string): Promise<boolean> {
- const cmd = content.toLowerCase().trim();
+ const trimmed = content.trim();
+ const cmd = trimmed.toLowerCase();
const channel = this.channels.get(channelType as any);
if (!channel) return false;
@@ -581,15 +597,12 @@ 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}`,
+ `Telegram access: ${getTelegramAccessSummary(config)}`,
`Budget: ${budget.getStatusText()}`,
`Skills: ${ctx.skillNames().length > 0 ? ctx.skillNames().join(', ') : 'none'}`,
];
@@ -597,6 +610,208 @@ export class Agent {
return true;
}
+ if (cmd.startsWith('/telegram')) {
+ if (channelType !== 'cli') {
+ await channel.send('`/telegram` is only available from the Mercury CLI chat.', channelId);
+ return true;
+ }
+
+ const config = ctx.config();
+ const rawSubcommand = trimmed.slice('/telegram'.length).trim();
+ if (!rawSubcommand && channel instanceof CLIChannel) {
+ await channel.withMenu(async (select) => {
+ await this.openCliTelegramMenu(channel, channelId, select);
+ });
+ return true;
+ }
+
+ const parts = rawSubcommand.split(/\s+/).filter(Boolean);
+ const action = parts[0]?.toLowerCase() || 'help';
+ const formatTelegramUser = (user: {
+ userId: number;
+ username?: string;
+ firstName?: string;
+ pairingCode?: string;
+ }) => {
+ const username = user.username ? ` (@${user.username})` : '';
+ const firstName = user.firstName ? ` ${user.firstName}` : '';
+ const pairingCode = user.pairingCode ? ` [code: ${user.pairingCode}]` : '';
+ return `${user.userId}${username}${firstName}${pairingCode}`;
+ };
+
+ const sendTelegramOverview = async () => {
+ const lines = [
+ '**Telegram Management**',
+ '',
+ `Access: ${getTelegramAccessSummary(config)}`,
+ `Admins: ${config.channels.telegram.admins.length > 0 ? config.channels.telegram.admins.map(formatTelegramUser).join(', ') : 'none'}`,
+ `Members: ${config.channels.telegram.members.length > 0 ? config.channels.telegram.members.map(formatTelegramUser).join(', ') : 'none'}`,
+ `Pending: ${config.channels.telegram.pending.length > 0 ? config.channels.telegram.pending.map(formatTelegramUser).join(', ') : 'none'}`,
+ '',
+ 'Commands:',
+ '• `/telegram pending`',
+ '• `/telegram users`',
+ '• `/telegram approve <pairing-code|user-id>`',
+ '• `/telegram reject <user-id>`',
+ '• `/telegram remove <user-id>`',
+ '• `/telegram promote <user-id>`',
+ '• `/telegram demote <user-id>`',
+ '• `/telegram reset`',
+ ];
+ await channel.send(lines.join('\n'), channelId);
+ };
+
+ if (action === 'help' || action === 'status') {
+ await sendTelegramOverview();
+ return true;
+ }
+
+ if (action === 'pending') {
+ const pending = getTelegramPendingRequests(config);
+ const lines = [
+ '**Telegram Pending Requests**',
+ '',
+ pending.length > 0 ? pending.map(formatTelegramUser).join('\n') : 'No pending Telegram requests.',
+ ];
+ await channel.send(lines.join('\n'), channelId);
+ return true;
+ }
+
+ if (action === 'users') {
+ const approved = getTelegramApprovedUsers(config);
+ const lines = [
+ '**Telegram Approved Users**',
+ '',
+ `Admins: ${config.channels.telegram.admins.length > 0 ? config.channels.telegram.admins.map(formatTelegramUser).join(', ') : 'none'}`,
+ `Members: ${config.channels.telegram.members.length > 0 ? config.channels.telegram.members.map(formatTelegramUser).join(', ') : 'none'}`,
+ '',
+ `Total approved: ${approved.length}`,
+ ];
+ await channel.send(lines.join('\n'), channelId);
+ return true;
+ }
+
+ if (action === 'approve') {
+ const value = parts[1];
+ if (!value) {
+ await channel.send('Usage: `/telegram approve <pairing-code|user-id>`', channelId);
+ return true;
+ }
+
+ let approved = approveTelegramPendingRequestByPairingCode(config, value);
+ let resultLabel = value;
+
+ if (!approved) {
+ const userId = Number(value);
+ if (!isNaN(userId)) {
+ approved = approveTelegramPendingRequest(config, userId, 'member');
+ resultLabel = userId.toString();
+ }
+ }
+
+ if (!approved) {
+ await channel.send(`No pending Telegram request found for \`${resultLabel}\`.`, channelId);
+ return true;
+ }
+
+ saveConfig(config);
+ await channel.send(`Approved Telegram user ${formatTelegramUser(approved)}.`, channelId);
+ return true;
+ }
+
+ if (action === 'reject') {
+ const value = Number(parts[1]);
+ if (isNaN(value)) {
+ await channel.send('Usage: `/telegram reject <user-id>`', channelId);
+ return true;
+ }
+
+ const rejected = rejectTelegramPendingRequest(config, value);
+ if (!rejected) {
+ await channel.send(`No pending Telegram request found for \`${value}\`.`, channelId);
+ return true;
+ }
+
+ saveConfig(config);
+ await channel.send(`Rejected Telegram request for ${formatTelegramUser(rejected)}.`, channelId);
+ return true;
+ }
+
+ if (action === 'remove') {
+ const value = Number(parts[1]);
+ if (isNaN(value)) {
+ await channel.send('Usage: `/telegram remove <user-id>`', channelId);
+ return true;
+ }
+
+ const removed = removeTelegramUser(config, value);
+ if (!removed) {
+ await channel.send(`No approved Telegram user found for \`${value}\`.`, channelId);
+ return true;
+ }
+
+ saveConfig(config);
+ await channel.send(`Removed Telegram access for ${formatTelegramUser(removed)}.`, channelId);
+ return true;
+ }
+
+ if (action === 'promote') {
+ const value = Number(parts[1]);
+ if (isNaN(value)) {
+ await channel.send('Usage: `/telegram promote <user-id>`', channelId);
+ return true;
+ }
+
+ const promoted = promoteTelegramUserToAdmin(config, value);
+ if (!promoted) {
+ await channel.send(`No Telegram member found for \`${value}\`.`, channelId);
+ return true;
+ }
+
+ saveConfig(config);
+ await channel.send(`Promoted ${formatTelegramUser(promoted)} to Telegram admin.`, channelId);
+ return true;
+ }
+
+ if (action === 'demote') {
+ const value = Number(parts[1]);
+ if (isNaN(value)) {
+ await channel.send('Usage: `/telegram demote <user-id>`', channelId);
+ return true;
+ }
+
+ const demoted = demoteTelegramAdmin(config, value);
+ if (!demoted) {
+ await channel.send('Could not demote that Telegram admin. Mercury must keep at least one admin.', channelId);
+ return true;
+ }
+
+ saveConfig(config);
+ await channel.send(`Demoted ${formatTelegramUser(demoted)} to Telegram member.`, channelId);
+ return true;
+ }
+
+ if (action === 'reset' || action === 'unpair') {
+ config.channels.telegram.admins = [];
+ config.channels.telegram.members = [];
+ config.channels.telegram.pending = [];
+ saveConfig(config);
+ await channel.send('Telegram access reset. New users can send /start to begin pairing again.', channelId);
+ return true;
+ }
+
+ await channel.send(
+ `Unknown Telegram command "${action}". Try \`/telegram\`, \`/telegram pending\`, or \`/telegram users\`.`,
+ channelId,
+ );
+ return true;
+ }
+
+ if ((cmd === '/' || cmd === '/menu') && channelType === 'cli' && channel instanceof CLIChannel) {
+ await this.openCliCommandMenu(channel, channelId);
+ return true;
+ }
+
if (cmd === '/tools') {
const tools = ctx.toolNames();
const grouped = [
@@ -653,4 +868,257 @@ export class Agent {
return false;
}
+
+ private async openCliCommandMenu(channel: CLIChannel, channelId: string): Promise<void> {
+ const ctx = this.capabilities.getChatCommandContext();
+ if (!ctx) return;
+
+ await channel.withMenu(async (select) => {
+ while (true) {
+ const streamLabel = this.telegramStreaming ? 'Disable Telegram Streaming' : 'Enable Telegram Streaming';
+ const action = await select('Mercury Commands', [
+ { value: 'status', label: 'Status' },
+ { value: 'telegram', label: 'Telegram' },
+ { value: 'tools', label: 'Tools' },
+ { value: 'skills', label: 'Skills' },
+ { value: 'stream', label: streamLabel },
+ { value: 'help', label: 'Help' },
+ { value: 'exit', label: 'Exit' },
+ ]);
+
+ if (action === 'exit') {
+ return;
+ }
+
+ if (action === 'status') {
+ await this.handleChatCommand('/status', 'cli', channelId);
+ continue;
+ }
+
+ if (action === 'telegram') {
+ await this.openCliTelegramMenu(channel, channelId, select);
+ continue;
+ }
+
+ if (action === 'tools') {
+ await this.handleChatCommand('/tools', 'cli', channelId);
+ continue;
+ }
+
+ if (action === 'skills') {
+ await this.handleChatCommand('/skills', 'cli', channelId);
+ continue;
+ }
+
+ if (action === 'stream') {
+ await this.handleChatCommand('/stream', 'cli', channelId);
+ continue;
+ }
+
+ if (action === 'help') {
+ await channel.send(ctx.manual(), channelId);
+ }
+ }
+ });
+ }
+
+ private async openCliTelegramMenu(
+ channel: CLIChannel,
+ channelId: string,
+ select: (title: string, options: ArrowSelectOption[]) => Promise<string>,
+ ): Promise<void> {
+ const ctx = this.capabilities.getChatCommandContext();
+ if (!ctx) return;
+ const formatTelegramUser = (user: {
+ userId: number;
+ username?: string;
+ firstName?: string;
+ pairingCode?: string;
+ }) => {
+ const username = user.username ? ` (@${user.username})` : '';
+ const firstName = user.firstName ? ` ${user.firstName}` : '';
+ const pairingCode = user.pairingCode ? ` [code: ${user.pairingCode}]` : '';
+ return `${user.userId}${username}${firstName}${pairingCode}`;
+ };
+
+ const selectFromUsers = async (
+ title: string,
+ users: Array<{ userId: number; username?: string; firstName?: string; pairingCode?: string }>,
+ emptyMessage: string,
+ backValue: string = 'back',
+ ): Promise<string> => {
+ if (users.length === 0) {
+ await channel.send(emptyMessage, channelId);
+ return backValue;
+ }
+
+ return select(title, [
+ ...users.map((user) => ({
+ value: user.pairingCode || user.userId.toString(),
+ label: formatTelegramUser(user),
+ })),
+ { value: backValue, label: 'Back' },
+ ]);
+ };
+
+ while (true) {
+ const config = ctx.config();
+ const action = await select('Telegram Commands', [
+ { value: 'overview', label: 'Overview' },
+ { value: 'pending', label: `Pending Requests (${config.channels.telegram.pending.length})` },
+ { value: 'users', label: `Approved Users (${getTelegramApprovedUsers(config).length})` },
+ { value: 'approve', label: 'Approve Request' },
+ { value: 'reject', label: 'Reject Request' },
+ { value: 'remove', label: 'Remove User' },
+ { value: 'promote', label: 'Promote to Admin' },
+ { value: 'demote', label: 'Demote Admin' },
+ { value: 'reset', label: 'Reset Telegram Access' },
+ { value: 'back', label: 'Back' },
+ { value: 'exit', label: 'Exit' },
+ ]);
+
+ if (action === 'exit') {
+ return;
+ }
+
+ if (action === 'back') {
+ return;
+ }
+
+ if (action === 'overview') {
+ await this.handleChatCommand('/telegram status', 'cli', channelId);
+ continue;
+ }
+
+ if (action === 'pending') {
+ await this.handleChatCommand('/telegram pending', 'cli', channelId);
+ continue;
+ }
+
+ if (action === 'users') {
+ await this.handleChatCommand('/telegram users', 'cli', channelId);
+ continue;
+ }
+
+ if (action === 'approve') {
+ const pending = getTelegramPendingRequests(config);
+ const selected = await selectFromUsers(
+ 'Approve Telegram Request',
+ pending,
+ 'There are no pending Telegram requests to approve.',
+ );
+
+ if (selected === 'back') {
+ continue;
+ }
+
+ await this.handleChatCommand(`/telegram approve ${selected}`, 'cli', channelId);
+ continue;
+ }
+
+ if (action === 'reject') {
+ const pending = getTelegramPendingRequests(config);
+ const selected = await selectFromUsers(
+ 'Reject Telegram Request',
+ pending,
+ 'There are no pending Telegram requests to reject.',
+ );
+
+ if (selected === 'back') {
+ continue;
+ }
+
+ const request = pending.find((entry) => (entry.pairingCode || entry.userId.toString()) === selected);
+ if (!request) {
+ await channel.send('That Telegram request is no longer pending.', channelId);
+ continue;
+ }
+
+ await this.handleChatCommand(`/telegram reject ${request.userId}`, 'cli', channelId);
+ continue;
+ }
+
+ if (action === 'remove') {
+ const approved = getTelegramApprovedUsers(config);
+ const selected = await selectFromUsers(
+ 'Remove Telegram User',
+ approved,
+ 'There are no approved Telegram users to remove.',
+ );
+
+ if (selected === 'back') {
+ continue;
+ }
+
+ const user = approved.find((entry) => entry.userId.toString() === selected);
+ if (!user) {
+ await channel.send('That Telegram user is no longer approved.', channelId);
+ continue;
+ }
+
+ await this.handleChatCommand(`/telegram remove ${user.userId}`, 'cli', channelId);
+ continue;
+ }
+
+ if (action === 'promote') {
+ const members = config.channels.telegram.members;
+ const selected = await selectFromUsers(
+ 'Promote Telegram Member',
+ members,
+ 'There are no Telegram members available to promote.',
+ );
+
+ if (selected === 'back') {
+ continue;
+ }
+
+ const member = members.find((entry) => entry.userId.toString() === selected);
+ if (!member) {
+ await channel.send('That Telegram member is no longer available.', channelId);
+ continue;
+ }
+
+ await this.handleChatCommand(`/telegram promote ${member.userId}`, 'cli', channelId);
+ continue;
+ }
+
+ if (action === 'demote') {
+ const admins = config.channels.telegram.admins;
+ const selected = await selectFromUsers(
+ 'Demote Telegram Admin',
+ admins,
+ 'There are no Telegram admins available to demote.',
+ );
+
+ if (selected === 'back') {
+ continue;
+ }
+
+ const admin = admins.find((entry) => entry.userId.toString() === selected);
+ if (!admin) {
+ await channel.send('That Telegram admin is no longer available.', channelId);
+ continue;
+ }
+
+ await this.handleChatCommand(`/telegram demote ${admin.userId}`, 'cli', channelId);
+ continue;
+ }
+
+ if (action === 'reset') {
+ const confirmation = await select('Reset Telegram Access?', [
+ { value: 'cancel', label: 'Cancel' },
+ { value: 'confirm', label: 'Reset all Telegram access' },
+ { value: 'back', label: 'Back' },
+ ]);
+
+ if (confirmation === 'confirm') {
+ clearTelegramAccess(config);
+ saveConfig(config);
+ await channel.send('Telegram access reset. New users can send /start to begin pairing again.', channelId);
+ }
+
+ continue;
+ }
+ }
+ }
}
diff --git a/src/index.ts b/src/index.ts
index 9e168b16..154e5639 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -5,7 +5,25 @@ import { Command } from 'commander';
import readline from 'node:readline';
import chalk from 'chalk';
import figlet from 'figlet';
-import { loadConfig, saveConfig, isSetupComplete, getMercuryHome, ensureCreatorField, clearTelegramPairing, isProviderConfigured } from './utils/config.js';
+import {
+ loadConfig,
+ saveConfig,
+ isSetupComplete,
+ getMercuryHome,
+ ensureCreatorField,
+ clearTelegramAccess,
+ isProviderConfigured,
+ getTelegramAccessSummary,
+ getTelegramApprovedUsers,
+ getTelegramPendingRequests,
+ approveTelegramPendingRequest,
+ approveTelegramPendingRequestByPairingCode,
+ rejectTelegramPendingRequest,
+ removeTelegramUser,
+ promoteTelegramUserToAdmin,
+ demoteTelegramAdmin,
+ hasTelegramAdmins,
+} from './utils/config.js';
import type { MercuryConfig } from './utils/config.js';
import type { ProviderName } from './utils/config.js';
import { logger } from './utils/logger.js';
@@ -418,6 +436,83 @@ function parseGithubRepo(input: string): { owner: string; repo: string } | null
return null;
}
+function formatTelegramUser(user: {
+ userId: number;
+ username?: string;
+ firstName?: string;
+}): string {
+ const username = user.username ? ` (@${user.username})` : '';
+ const firstName = user.firstName ? ` ${user.firstName}` : '';
+ return `${user.userId}${username}${firstName}`;
+}
+
+function printTelegramAccessState(config: MercuryConfig): void {
+ const admins = config.channels.telegram.admins;
+ const members = config.channels.telegram.members;
+ const pending = config.channels.telegram.pending;
+ const pendingSummary = pending.length > 0
+ ? pending.map((entry) => {
+ const code = entry.pairingCode ? ` [code: ${entry.pairingCode}]` : '';
+ return `${formatTelegramUser(entry)}${code}`;
+ }).join(', ')
+ : '';
+
+ console.log('');
+ console.log(` Telegram Access: ${chalk.white(getTelegramAccessSummary(config))}`);
+ console.log(` Admins: ${admins.length > 0 ? chalk.green(admins.map(formatTelegramUser).join(', ')) : chalk.dim('none')}`);
+ console.log(` Members: ${members.length > 0 ? chalk.green(members.map(formatTelegramUser).join(', ')) : chalk.dim('none')}`);
+ console.log(` Pending: ${pending.length > 0 ? chalk.yellow(pendingSummary) : chalk.dim('none')}`);
+}
+
+function restartDaemonIfRunning(message?: string): void {
+ const daemon = getDaemonStatus();
+ if (!daemon.running) return;
+
+ if (message) {
+ console.log(chalk.dim(` ${message}`));
+ }
+ restartDaemon();
+}
+
+async function completeInitialTelegramPairing(config: MercuryConfig): Promise<void> {
+ if (!config.channels.telegram.enabled || !config.channels.telegram.botToken || hasTelegramAdmins(config)) {
+ return;
+ }
+
+ console.log('');
+ console.log(chalk.bold.white(' Telegram Pairing'));
+ console.log(chalk.dim(' 1. Open Telegram and message your bot.'));
+ console.log(chalk.dim(' 2. Send /start to receive your pairing code in Telegram.'));
+ console.log(chalk.dim(' 3. Paste that pairing code below to finish setup.'));
+ console.log('');
+
+ const telegram = new TelegramChannel(config);
+ try {
+ await telegram.start();
+
+ while (true) {
+ const pairingCode = await ask(chalk.white(' Telegram Pairing Code: '));
+ if (!pairingCode) {
+ console.log(chalk.red(' Telegram pairing code is required to continue.'));
+ continue;
+ }
+
+ const approved = approveTelegramPendingRequestByPairingCode(config, pairingCode);
+ if (!approved) {
+ console.log(chalk.red(' That pairing code is not valid yet. Send /start in Telegram, then paste the exact code here.'));
+ continue;
+ }
+
+ saveConfig(config);
+ console.log(chalk.green(` ✓ Telegram paired. First admin: ${formatTelegramUser(approved)}.`));
+ console.log('');
+ break;
+ }
+ } finally {
+ await telegram.stop();
+ }
+}
+
async function configure(existingConfig?: MercuryConfig): Promise<void> {
const isReconfig = !!existingConfig;
const config = existingConfig ?? loadConfig();
@@ -589,6 +684,8 @@ async function configure(existingConfig?: MercuryConfig): Promise<void> {
console.log(chalk.dim(' 2. Run /newbot and follow the prompts'));
console.log(chalk.dim(' 3. Copy the bot token BotFather gives you'));
console.log(chalk.dim(' 4. Paste that token here'));
+ console.log(chalk.dim(' After setup, users send /start to request access.'));
+ console.log(chalk.dim(' The first Telegram user gets a pairing code, and you approve that code from the CLI.'));
}
console.log('');
@@ -597,15 +694,17 @@ async function configure(existingConfig?: MercuryConfig): Promise<void> {
if (isReconfig && telegramToken.toLowerCase() === 'none') {
config.channels.telegram.enabled = false;
config.channels.telegram.botToken = '';
- clearTelegramPairing(config);
+ clearTelegramAccess(config);
} else if (telegramToken) {
if (telegramToken !== config.channels.telegram.botToken) {
- clearTelegramPairing(config);
+ clearTelegramAccess(config);
}
config.channels.telegram.botToken = telegramToken;
config.channels.telegram.enabled = true;
}
+ await completeInitialTelegramPairing(config);
+
hr();
console.log('');
console.log(chalk.bold.white(' GitHub Integration (optional)'));
@@ -776,28 +875,37 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
});
capabilities.setSendFileHandler(async (filePath: string) => {
- const msg = channels.getActiveChannels().includes('telegram')
- ? channels.get('telegram')
- : channels.get('cli');
- if (msg) {
- await msg.sendFile(filePath);
+ const { channelId, channelType } = capabilities.getChannelContext();
+ const telegram = channels.get('telegram');
+
+ if (channelType === 'telegram' && telegram) {
+ await telegram.sendFile(filePath, channelId);
+ return;
+ }
+
+ if (config.channels.telegram.enabled && telegram && getTelegramApprovedUsers(config).length > 0) {
+ await telegram.sendFile(filePath);
+ return;
+ }
+
+ const cli = channels.get('cli');
+ if (cli) {
+ await cli.sendFile(filePath);
}
});
capabilities.setSendMessageHandler(async (content: string) => {
const telegram = channels.get('telegram');
- const pairedChatId = config.channels.telegram.pairedChatId;
- const pairedUserId = config.channels.telegram.pairedUserId;
if (!config.channels.telegram.enabled || !telegram) {
throw new Error('Telegram is not configured. Add a bot token in setup or run `mercury doctor`.');
}
- if (pairedChatId == null || pairedUserId == null) {
- throw new Error('Telegram is not paired. Complete the pairing flow with /start or /pair from the Telegram owner account.');
+ if (getTelegramApprovedUsers(config).length === 0) {
+ throw new Error('Telegram has no approved users. Ask someone to send /start, then approve the request from Mercury.');
}
- await telegram.send(content, `telegram:${pairedChatId}`);
+ await telegram.send(content);
});
if (process.env.GITHUB_TOKEN) {
setGitHubToken(process.env.GITHUB_TOKEN);
@@ -985,12 +1093,13 @@ program
}
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(` Telegram Access: ${chalk.white(getTelegramAccessSummary(config))}`);
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')}`);
console.log(` Daemon: ${daemon.running ? chalk.green(`running (PID: ${daemon.pid})`) : chalk.dim('not running')}`);
console.log(` Home: ${chalk.dim(home)}`);
+ printTelegramAccessState(config);
console.log('');
});
@@ -1003,31 +1112,199 @@ program
const telegramCmd = program
.command('telegram')
- .description('Manage Telegram pairing and access');
+ .description('Manage Telegram access approvals and admins');
+
+telegramCmd
+ .command('list')
+ .description('Show approved Telegram users and pending access requests')
+ .action(() => {
+ const config = loadConfig();
+ console.log('');
+ printTelegramAccessState(config);
+ console.log('');
+ });
+
+telegramCmd
+ .command('approve <codeOrUserId>')
+ .description('Approve a pending Telegram access request by pairing code or user ID')
+ .action((codeOrUserId: string) => {
+ const config = loadConfig();
+ const hasAdmins = hasTelegramAdmins(config);
+
+ if (!hasAdmins) {
+ const approved = approveTelegramPendingRequestByPairingCode(config, codeOrUserId.trim());
+ if (!approved) {
+ console.log('');
+ console.log(chalk.red(` No pending first-time Telegram pairing found for code ${codeOrUserId}.`));
+ console.log('');
+ return;
+ }
+
+ saveConfig(config);
+ console.log('');
+ console.log(chalk.green(` ✓ Approved first Telegram admin ${formatTelegramUser(approved)}.`));
+ restartDaemonIfRunning('Restarting the background daemon to apply the change immediately...');
+ console.log('');
+ return;
+ }
+
+ const targetUserId = Number(codeOrUserId);
+ if (isNaN(targetUserId)) {
+ console.log('');
+ console.log(chalk.red(' Please provide a numeric Telegram user ID once Telegram already has an admin.'));
+ console.log('');
+ return;
+ }
+
+ const approved = approveTelegramPendingRequest(config, targetUserId, 'member');
+ if (!approved) {
+ console.log('');
+ console.log(chalk.red(` No pending Telegram request found for user ${codeOrUserId}.`));
+ console.log('');
+ return;
+ }
+
+ saveConfig(config);
+ console.log('');
+ console.log(chalk.green(` ✓ Approved Telegram member ${formatTelegramUser(approved)}.`));
+ restartDaemonIfRunning('Restarting the background daemon to apply the change immediately...');
+ console.log('');
+ });
+
+telegramCmd
+ .command('reject <userId>')
+ .description('Reject a pending Telegram access request')
+ .action((userId: string) => {
+ const config = loadConfig();
+ const targetUserId = Number(userId);
+ if (isNaN(targetUserId)) {
+ console.log('');
+ console.log(chalk.red(' Please provide a numeric Telegram user ID.'));
+ console.log('');
+ return;
+ }
+
+ const rejected = rejectTelegramPendingRequest(config, targetUserId);
+ if (!rejected) {
+ console.log('');
+ console.log(chalk.red(` No pending Telegram request found for user ${userId}.`));
+ console.log('');
+ return;
+ }
+
+ saveConfig(config);
+ console.log('');
+ console.log(chalk.green(` ✓ Rejected Telegram request for ${formatTelegramUser(rejected)}.`));
+ restartDaemonIfRunning('Restarting the background daemon to apply the change immediately...');
+ console.log('');
+ });
+
+telegramCmd
+ .command('remove <userId>')
+ .description('Remove an approved Telegram admin or member')
+ .action((userId: string) => {
+ const config = loadConfig();
+ const targetUserId = Number(userId);
+ if (isNaN(targetUserId)) {
+ console.log('');
+ console.log(chalk.red(' Please provide a numeric Telegram user ID.'));
+ console.log('');
+ return;
+ }
+
+ const removed = removeTelegramUser(config, targetUserId);
+ if (!removed) {
+ console.log('');
+ console.log(chalk.red(` No approved Telegram user found for ${userId}.`));
+ console.log('');
+ return;
+ }
+
+ saveConfig(config);
+ console.log('');
+ console.log(chalk.green(` ✓ Removed Telegram access for ${formatTelegramUser(removed)}.`));
+ restartDaemonIfRunning('Restarting the background daemon to apply the change immediately...');
+ console.log('');
+ });
+
+telegramCmd
+ .command('promote <userId>')
+ .description('Promote an approved Telegram member to admin')
+ .action((userId: string) => {
+ const config = loadConfig();
+ const targetUserId = Number(userId);
+ if (isNaN(targetUserId)) {
+ console.log('');
+ console.log(chalk.red(' Please provide a numeric Telegram user ID.'));
+ console.log('');
+ return;
+ }
+
+ const promoted = promoteTelegramUserToAdmin(config, targetUserId);
+ if (!promoted) {
+ console.log('');
+ console.log(chalk.red(` No Telegram member found for ${userId}.`));
+ console.log('');
+ return;
+ }
+
+ saveConfig(config);
+ console.log('');
+ console.log(chalk.green(` ✓ Promoted ${formatTelegramUser(promoted)} to Telegram admin.`));
+ restartDaemonIfRunning('Restarting the background daemon to apply the change immediately...');
+ console.log('');
+ });
+
+telegramCmd
+ .command('demote <userId>')
+ .description('Demote a Telegram admin to member')
+ .action((userId: string) => {
+ const config = loadConfig();
+ const targetUserId = Number(userId);
+ if (isNaN(targetUserId)) {
+ console.log('');
+ console.log(chalk.red(' Please provide a numeric Telegram user ID.'));
+ console.log('');
+ return;
+ }
+
+ const demoted = demoteTelegramAdmin(config, targetUserId);
+ if (!demoted) {
+ console.log('');
+ console.log(chalk.red(' Could not demote that Telegram admin. Mercury must keep at least one admin.'));
+ console.log('');
+ return;
+ }
+
+ saveConfig(config);
+ console.log('');
+ console.log(chalk.green(` ✓ Demoted ${formatTelegramUser(demoted)} to Telegram member.`));
+ restartDaemonIfRunning('Restarting the background daemon to apply the change immediately...');
+ console.log('');
+ });
telegramCmd
.command('unpair')
- .description('Clear the paired Telegram owner for this Mercury instance')
+ .description('Reset all Telegram access for this Mercury instance')
.action(() => {
const config = loadConfig();
- const daemon = getDaemonStatus();
- if (config.channels.telegram.pairedUserId == null) {
+ const hasAnyAccess = getTelegramApprovedUsers(config).length > 0 || getTelegramPendingRequests(config).length > 0;
+ if (!hasAnyAccess) {
console.log('');
- console.log(chalk.dim(' Telegram is already unpaired.'));
+ console.log(chalk.dim(' Telegram access is already empty.'));
console.log('');
return;
}
- clearTelegramPairing(config);
+ clearTelegramAccess(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(chalk.green(' ✓ Telegram access reset.'));
+ restartDaemonIfRunning('Restarting the background daemon to apply the change immediately...');
+ if (!getDaemonStatus().running) {
+ console.log(chalk.dim(' New private Telegram users can send /start to request access.'));
+ console.log(chalk.dim(' The first request must be approved from the CLI with `mercury telegram approve <pairing-code>`.'));
}
console.log('');
});
diff --git a/src/types/channel.ts b/src/types/channel.ts
index d587953b..2b494dc6 100644
--- a/src/types/channel.ts
+++ b/src/types/channel.ts
@@ -1,3 +1,21 @@
+export interface TelegramAccessUser {
+ userId: number;
+ chatId: number;
+ username?: string;
+ firstName?: string;
+ requestedAt?: string;
+ approvedAt: string;
+}
+
+export interface TelegramPendingRequest {
+ userId: number;
+ chatId: number;
+ username?: string;
+ firstName?: string;
+ requestedAt: string;
+ pairingCode?: string;
+}
+
export type ChannelType = 'cli' | 'telegram' | 'internal' | 'signal' | 'discord' | 'slack' | 'whatsapp';
export interface ChannelMessage {
@@ -23,6 +41,9 @@ export interface TelegramChannelConfig extends ChannelConfig {
webhookUrl?: string;
allowedChatIds?: number[];
streaming?: boolean;
+ admins?: TelegramAccessUser[];
+ members?: TelegramAccessUser[];
+ pending?: TelegramPendingRequest[];
pairedUserId?: number;
pairedChatId?: number;
pairedUsername?: string;
diff --git a/src/types/index.ts b/src/types/index.ts
index fdc32631..f21c63b1 100644
--- a/src/types/index.ts
+++ b/src/types/index.ts
@@ -1,3 +1,11 @@
-export type { ChannelType, ChannelMessage, ChannelConfig, TelegramChannelConfig, CLIChannelConfig } from './channel.js';
+export type {
+ ChannelType,
+ ChannelMessage,
+ ChannelConfig,
+ TelegramChannelConfig,
+ CLIChannelConfig,
+ TelegramAccessUser,
+ TelegramPendingRequest,
+} from './channel.js';
export type { MessageRole, Message, SystemMessage, UserMessage, AssistantMessage, MessageSummary } from './message.js';
-export type { AgentState, AgentMode, AgentIdentity, AgentContext, TokenUsage, HeartbeatState } from './agent.js';
\ No newline at end of file
+export type { AgentState, AgentMode, AgentIdentity, AgentContext, TokenUsage, HeartbeatState } from './agent.js';
diff --git a/src/utils/config.ts b/src/utils/config.ts
index 8079b5fe..72677d49 100644
--- a/src/utils/config.ts
+++ b/src/utils/config.ts
@@ -24,6 +24,24 @@ export interface ProviderConfig {
enabled: boolean;
}
+export interface TelegramAccessUser {
+ userId: number;
+ chatId: number;
+ username?: string;
+ firstName?: string;
+ requestedAt?: string;
+ approvedAt: string;
+}
+
+export interface TelegramPendingRequest {
+ userId: number;
+ chatId: number;
+ username?: string;
+ firstName?: string;
+ requestedAt: string;
+ pairingCode?: string;
+}
+
export type ProviderName =
| 'openai'
| 'anthropic'
@@ -54,6 +72,9 @@ export interface MercuryConfig {
webhookUrl?: string;
allowedChatIds?: number[];
streaming?: boolean;
+ admins: TelegramAccessUser[];
+ members: TelegramAccessUser[];
+ pending: TelegramPendingRequest[];
pairedUserId?: number;
pairedChatId?: number;
pairedUsername?: string;
@@ -156,6 +177,9 @@ export function getDefaultConfig(): MercuryConfig {
.filter(Boolean)
.map(Number),
streaming: getEnvBool('TELEGRAM_STREAMING', true),
+ admins: [],
+ members: [],
+ pending: [],
},
},
github: {
@@ -184,9 +208,9 @@ export function loadConfig(): MercuryConfig {
const raw = readFileSync(CONFIG_PATH, 'utf-8');
const fileConfig = parseYaml(raw) as Partial<MercuryConfig>;
const defaults = getDefaultConfig();
- return deepMerge(defaults, fileConfig);
+ return migrateLegacyTelegramAccess(deepMerge(defaults, fileConfig));
}
- return getDefaultConfig();
+ return migrateLegacyTelegramAccess(getDefaultConfig());
}
export function saveConfig(config: MercuryConfig): void {
@@ -246,16 +270,203 @@ export function isProviderConfigured(provider: ProviderConfig): boolean {
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 getTelegramApprovedUsers(config: MercuryConfig): TelegramAccessUser[] {
+ return [
+ ...config.channels.telegram.admins,
+ ...config.channels.telegram.members,
+ ];
}
-export function clearTelegramPairing(config: MercuryConfig): MercuryConfig {
+export function getTelegramApprovedChatIds(config: MercuryConfig): number[] {
+ return [...new Set(getTelegramApprovedUsers(config).map((user) => user.chatId))];
+}
+
+export function getTelegramAdmins(config: MercuryConfig): TelegramAccessUser[] {
+ return config.channels.telegram.admins;
+}
+
+export function getTelegramPendingRequests(config: MercuryConfig): TelegramPendingRequest[] {
+ return config.channels.telegram.pending;
+}
+
+export function findTelegramApprovedUser(config: MercuryConfig, userId: number): TelegramAccessUser | undefined {
+ return getTelegramApprovedUsers(config).find((user) => user.userId === userId);
+}
+
+export function findTelegramAdmin(config: MercuryConfig, userId: number): TelegramAccessUser | undefined {
+ return config.channels.telegram.admins.find((user) => user.userId === userId);
+}
+
+export function findTelegramPendingRequest(config: MercuryConfig, userId: number): TelegramPendingRequest | undefined {
+ return config.channels.telegram.pending.find((request) => request.userId === userId);
+}
+
+export function findTelegramPendingRequestByPairingCode(
+ config: MercuryConfig,
+ pairingCode: string,
+): TelegramPendingRequest | undefined {
+ return config.channels.telegram.pending.find((request) => request.pairingCode === pairingCode);
+}
+
+export function hasTelegramAdmins(config: MercuryConfig): boolean {
+ return config.channels.telegram.admins.length > 0;
+}
+
+export function getTelegramAccessSummary(config: MercuryConfig): string {
+ return `${config.channels.telegram.admins.length} admin${config.channels.telegram.admins.length === 1 ? '' : 's'}, `
+ + `${config.channels.telegram.members.length} member${config.channels.telegram.members.length === 1 ? '' : 's'}, `
+ + `${config.channels.telegram.pending.length} pending`;
+}
+
+export function addTelegramPendingRequest(
+ config: MercuryConfig,
+ request: Omit<TelegramPendingRequest, 'requestedAt'> & { requestedAt?: string },
+): TelegramPendingRequest {
+ const existing = findTelegramPendingRequest(config, request.userId);
+ if (existing) {
+ existing.chatId = request.chatId;
+ existing.username = request.username || existing.username;
+ existing.firstName = request.firstName || existing.firstName;
+ existing.pairingCode = request.pairingCode || existing.pairingCode;
+ return existing;
+ }
+
+ const created: TelegramPendingRequest = {
+ ...request,
+ requestedAt: request.requestedAt || new Date().toISOString(),
+ };
+ config.channels.telegram.pending.push(created);
+ return created;
+}
+
+export function approveTelegramPendingRequest(
+ config: MercuryConfig,
+ userId: number,
+ role: 'admin' | 'member' = 'member',
+): TelegramAccessUser | null {
+ const request = findTelegramPendingRequest(config, userId);
+ if (!request) return null;
+
+ const approvedUser: TelegramAccessUser = {
+ userId: request.userId,
+ chatId: request.chatId,
+ username: request.username,
+ firstName: request.firstName,
+ requestedAt: request.requestedAt,
+ approvedAt: new Date().toISOString(),
+ };
+
+ config.channels.telegram.pending = config.channels.telegram.pending
+ .filter((entry) => entry.userId !== userId);
+ config.channels.telegram.admins = config.channels.telegram.admins
+ .filter((entry) => entry.userId !== userId);
+ config.channels.telegram.members = config.channels.telegram.members
+ .filter((entry) => entry.userId !== userId);
+
+ if (role === 'admin') {
+ config.channels.telegram.admins.push(approvedUser);
+ } else {
+ config.channels.telegram.members.push(approvedUser);
+ }
+
+ return approvedUser;
+}
+
+export function approveTelegramPendingRequestByPairingCode(
+ config: MercuryConfig,
+ pairingCode: string,
+): TelegramAccessUser | null {
+ const request = findTelegramPendingRequestByPairingCode(config, pairingCode);
+ if (!request) return null;
+ const role = hasTelegramAdmins(config) ? 'member' : 'admin';
+ return approveTelegramPendingRequest(config, request.userId, role);
+}
+
+export function rejectTelegramPendingRequest(config: MercuryConfig, userId: number): TelegramPendingRequest | null {
+ const request = findTelegramPendingRequest(config, userId);
+ if (!request) return null;
+ config.channels.telegram.pending = config.channels.telegram.pending
+ .filter((entry) => entry.userId !== userId);
+ return request;
+}
+
+export function removeTelegramUser(config: MercuryConfig, userId: number): TelegramAccessUser | null {
+ const admin = config.channels.telegram.admins.find((entry) => entry.userId === userId);
+ if (admin) {
+ config.channels.telegram.admins = config.channels.telegram.admins
+ .filter((entry) => entry.userId !== userId);
+ return admin;
+ }
+
+ const member = config.channels.telegram.members.find((entry) => entry.userId === userId);
+ if (member) {
+ config.channels.telegram.members = config.channels.telegram.members
+ .filter((entry) => entry.userId !== userId);
+ return member;
+ }
+
+ return null;
+}
+
+export function promoteTelegramUserToAdmin(config: MercuryConfig, userId: number): TelegramAccessUser | null {
+ const member = config.channels.telegram.members.find((entry) => entry.userId === userId);
+ if (!member) return null;
+ config.channels.telegram.members = config.channels.telegram.members
+ .filter((entry) => entry.userId !== userId);
+ config.channels.telegram.admins.push(member);
+ return member;
+}
+
+export function demoteTelegramAdmin(config: MercuryConfig, userId: number): TelegramAccessUser | null {
+ if (config.channels.telegram.admins.length <= 1) {
+ return null;
+ }
+
+ const admin = config.channels.telegram.admins.find((entry) => entry.userId === userId);
+ if (!admin) return null;
+ config.channels.telegram.admins = config.channels.telegram.admins
+ .filter((entry) => entry.userId !== userId);
+ config.channels.telegram.members.push(admin);
+ return admin;
+}
+
+export function clearTelegramAccess(config: MercuryConfig): MercuryConfig {
+ config.channels.telegram.admins = [];
+ config.channels.telegram.members = [];
+ config.channels.telegram.pending = [];
delete config.channels.telegram.pairedUserId;
delete config.channels.telegram.pairedChatId;
delete config.channels.telegram.pairedUsername;
return config;
}
+
+export function clearTelegramPairing(config: MercuryConfig): MercuryConfig {
+ return clearTelegramAccess(config);
+}
+
+export function migrateLegacyTelegramAccess(config: MercuryConfig): MercuryConfig {
+ const telegram = config.channels.telegram;
+ telegram.admins = telegram.admins || [];
+ telegram.members = telegram.members || [];
+ telegram.pending = telegram.pending || [];
+
+ if (
+ telegram.admins.length === 0
+ && telegram.members.length === 0
+ && typeof telegram.pairedUserId === 'number'
+ && typeof telegram.pairedChatId === 'number'
+ ) {
+ telegram.admins.push({
+ userId: telegram.pairedUserId,
+ chatId: telegram.pairedChatId,
+ username: telegram.pairedUsername,
+ approvedAt: new Date().toISOString(),
+ });
+ }
+
+ delete telegram.pairedUserId;
+ delete telegram.pairedChatId;
+ delete telegram.pairedUsername;
+
+ return config;
+}
diff --git a/src/utils/manual.ts b/src/utils/manual.ts
index a035962b..38b6d858 100644
--- a/src/utils/manual.ts
+++ b/src/utils/manual.ts
@@ -19,7 +19,7 @@ export function getManual(): string {
['edit_file', 'Replace specific text in a file', 'path, old_string, new_string'],
['list_dir', 'List directory contents', 'path'],
['delete_file', 'Delete a file', 'path'],
- ['send_message', 'Send a message to the paired Telegram owner', 'content'],
+ ['send_message', 'Send a message to approved Telegram users', 'content'],
['run_command', 'Execute a shell command', 'command'],
['approve_command', 'Permanently approve a command type', 'command (e.g. "curl")'],
['fetch_url', 'Fetch a URL and return content', 'url, format? (text/markdown)'],
@@ -59,7 +59,13 @@ 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 telegram list', 'Show Telegram admins, members, and pending requests'],
+ ['mercury telegram approve <code|id>', 'Approve the first Telegram pairing code or a later Telegram request'],
+ ['mercury telegram reject <id>', 'Reject a pending Telegram request'],
+ ['mercury telegram remove <id>', 'Remove an approved Telegram user'],
+ ['mercury telegram promote <id>', 'Promote a Telegram member to admin'],
+ ['mercury telegram demote <id>', 'Demote a Telegram admin to member'],
+ ['mercury telegram unpair', 'Reset all Telegram access'],
['mercury help', 'Show this manual'],
['mercury service install', 'Install as system service (auto-start)'],
['mercury service uninstall', 'Uninstall system service'],
@@ -77,16 +83,27 @@ export function getManual(): string {
sections.push('');
const chat = [
- ['/start', 'Pair this Telegram account to Mercury'],
- ['/pair', 'Pair this Telegram account to Mercury'],
+ ['/start', 'Start Telegram pairing or request Telegram access'],
+ ['/pair', 'Start Telegram pairing or request Telegram access'],
+ ['/', 'Open the CLI command picker with arrow-key navigation'],
+ ['/menu', 'Open the CLI command picker with arrow-key navigation'],
['/help', 'Show this manual'],
['/status', 'Show config and budget info'],
+ ['/telegram', 'CLI chat only: open the Telegram management menu'],
+ ['/telegram pending', 'CLI chat only: list pending Telegram requests'],
+ ['/telegram users', 'CLI chat only: list approved Telegram users'],
+ ['/telegram approve <code|id>', 'CLI chat only: approve the first pairing code or a later request'],
+ ['/telegram reject <id>', 'CLI chat only: reject a pending Telegram request'],
+ ['/telegram remove <id>', 'CLI chat only: remove an approved Telegram user'],
+ ['/telegram promote <id>', 'CLI chat only: promote a Telegram member to admin'],
+ ['/telegram demote <id>', 'CLI chat only: demote a Telegram admin to member'],
+ ['/telegram reset', 'CLI chat only: reset all Telegram access'],
['/tools', 'List currently loaded tools'],
['/skills', 'List installed skills'],
['/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'],
+ ['/unpair', 'Reset all Telegram access for this Mercury instance (admins only)'],
];
for (const [cmd, desc] of chat) {
diff --git a/src/utils/telegram-access.test.ts b/src/utils/telegram-access.test.ts
new file mode 100644
index 00000000..f4d47236
--- /dev/null
+++ b/src/utils/telegram-access.test.ts
@@ -0,0 +1,81 @@
+import { describe, expect, it } from 'vitest';
+import {
+ addTelegramPendingRequest,
+ approveTelegramPendingRequest,
+ approveTelegramPendingRequestByPairingCode,
+ clearTelegramAccess,
+ demoteTelegramAdmin,
+ findTelegramPendingRequestByPairingCode,
+ getDefaultConfig,
+ getTelegramAccessSummary,
+ getTelegramApprovedChatIds,
+ migrateLegacyTelegramAccess,
+ promoteTelegramUserToAdmin,
+ rejectTelegramPendingRequest,
+ removeTelegramUser,
+} from './config.js';
+
+describe('telegram access config helpers', () => {
+ it('migrates a legacy paired Telegram user into admins', () => {
+ const config = getDefaultConfig();
+ config.channels.telegram.pairedUserId = 42;
+ config.channels.telegram.pairedChatId = 77;
+ config.channels.telegram.pairedUsername = 'legacy_user';
+
+ migrateLegacyTelegramAccess(config);
+
+ expect(config.channels.telegram.admins).toHaveLength(1);
+ expect(config.channels.telegram.admins[0]).toMatchObject({
+ userId: 42,
+ chatId: 77,
+ username: 'legacy_user',
+ });
+ expect(config.channels.telegram.pairedUserId).toBeUndefined();
+ });
+
+ it('approves pending requests and reports summary counts', () => {
+ const config = getDefaultConfig();
+ addTelegramPendingRequest(config, { userId: 1, chatId: 101, username: 'alpha', pairingCode: '123456' });
+ addTelegramPendingRequest(config, { userId: 2, chatId: 202, username: 'beta' });
+
+ expect(findTelegramPendingRequestByPairingCode(config, '123456')?.userId).toBe(1);
+ const admin = approveTelegramPendingRequestByPairingCode(config, '123456');
+ const member = approveTelegramPendingRequest(config, 2, 'member');
+
+ expect(admin?.userId).toBe(1);
+ expect(member?.userId).toBe(2);
+ expect(getTelegramAccessSummary(config)).toBe('1 admin, 1 member, 0 pending');
+ expect(getTelegramApprovedChatIds(config)).toEqual([101, 202]);
+ });
+
+ it('supports reject, remove, promote, and demote flows', () => {
+ const config = getDefaultConfig();
+ addTelegramPendingRequest(config, { userId: 1, chatId: 101, username: 'alpha' });
+ addTelegramPendingRequest(config, { userId: 2, chatId: 202, username: 'beta' });
+ addTelegramPendingRequest(config, { userId: 3, chatId: 303, username: 'gamma' });
+
+ approveTelegramPendingRequest(config, 1, 'admin');
+ approveTelegramPendingRequest(config, 2, 'member');
+ expect(rejectTelegramPendingRequest(config, 3)?.userId).toBe(3);
+
+ expect(promoteTelegramUserToAdmin(config, 2)?.userId).toBe(2);
+ expect(demoteTelegramAdmin(config, 1)?.userId).toBe(1);
+ expect(removeTelegramUser(config, 1)?.userId).toBe(1);
+
+ expect(config.channels.telegram.admins).toHaveLength(1);
+ expect(config.channels.telegram.members).toHaveLength(0);
+ expect(config.channels.telegram.pending).toHaveLength(0);
+ });
+
+ it('clears all Telegram access state', () => {
+ const config = getDefaultConfig();
+ addTelegramPendingRequest(config, { userId: 1, chatId: 101 });
+ approveTelegramPendingRequest(config, 1, 'admin');
+
+ clearTelegramAccess(config);
+
+ expect(config.channels.telegram.admins).toEqual([]);
+ expect(config.channels.telegram.members).toEqual([]);
+ expect(config.channels.telegram.pending).toEqual([]);
+ });
+});