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.

fix telegram permission mode deadlock, editable status messages, /permissions command

Salman Qureshicae958370628
diff --git a/src/channels/telegram.ts b/src/channels/telegram.ts
index d788ed68..21e92082 100644
--- a/src/channels/telegram.ts
+++ b/src/channels/telegram.ts
@@ -21,6 +21,7 @@ import {
} from '../utils/config.js';
import { logger } from '../utils/logger.js';
import { mdToTelegram } from '../utils/markdown.js';
+import { formatToolStep, formatToolResult } from '../utils/tool-label.js';
const MAX_MESSAGE_LENGTH = 4096;
const ACCESS_ACTION_PREFIX = 'tg_access';
@@ -35,8 +36,11 @@ export class TelegramChannel extends BaseChannel {
private typingInterval: NodeJS.Timeout | null = null;
private chatCommandContext?: import('../capabilities/registry.js').ChatCommandContext;
private pendingApprovals: Map<string, ApprovalResolver> = new Map();
- private permissionModeAsked = new Set<number>();
+ private permissionModes = new Map<number, PermissionMode>();
private onPermissionMode?: (mode: PermissionMode, chatId: number) => void;
+ private statusMessageIds = new Map<string, number>();
+ private stepCounters = new Map<string, number>();
+ private statusText = new Map<string, string>();
constructor(private config: MercuryConfig) {
super();
@@ -50,6 +54,10 @@ export class TelegramChannel extends BaseChannel {
this.onPermissionMode = handler;
}
+ getPermissionMode(chatId: number): PermissionMode {
+ return this.permissionModes.get(chatId) ?? 'ask-me';
+ }
+
async start(): Promise<void> {
const token = this.config.channels.telegram.botToken;
if (!token) {
@@ -103,10 +111,14 @@ export class TelegramChannel extends BaseChannel {
this.lastActiveChatId = chatId;
logger.info({ chatId, text: ctx.message.text?.slice(0, 50) }, 'Telegram message received');
- if (!this.permissionModeAsked.has(chatId) && this.onPermissionMode) {
- this.permissionModeAsked.add(chatId);
- const mode = await this.askPermissionMode(`telegram:${chatId}`);
- this.onPermissionMode(mode, chatId);
+ if (!this.permissionModes.has(chatId) && this.onPermissionMode) {
+ this.askPermissionMode(`telegram:${chatId}`).then((mode) => {
+ this.permissionModes.set(chatId, mode);
+ if (this.onPermissionMode) {
+ this.onPermissionMode(mode, chatId);
+ }
+ }).catch(() => {});
+ this.permissionModes.set(chatId, 'ask-me');
}
if (command === '/unpair') {
@@ -123,6 +135,16 @@ export class TelegramChannel extends BaseChannel {
return;
}
+ if (command === '/permissions') {
+ this.askPermissionMode(`telegram:${chatId}`).then((mode) => {
+ this.permissionModes.set(chatId, mode);
+ if (this.onPermissionMode) {
+ this.onPermissionMode(mode, chatId);
+ }
+ }).catch(() => {});
+ return;
+ }
+
const msg: ChannelMessage = {
id: ctx.message.message_id.toString(),
channelId: `telegram:${chatId}`,
@@ -217,6 +239,8 @@ export class TelegramChannel extends BaseChannel {
{ command: 'budget_set', description: 'Set new daily token budget' },
{ command: 'stream', description: 'Toggle text streaming on/off' },
{ command: 'memory', description: 'View and manage second brain memory' },
+ { command: 'permissions', description: 'Change permission mode (Ask Me / Allow All)' },
+ { command: 'tasks', description: 'List scheduled tasks' },
{ command: 'unpair', description: 'Reset all Telegram access for this Mercury instance' },
];
@@ -305,6 +329,8 @@ export class TelegramChannel extends BaseChannel {
const chatIds = this.resolveTargetChatIds(targetId);
if (chatIds.length === 0 || !this.bot) return '';
+ this.deleteStatusMessage(targetId);
+
let full = '';
for await (const chunk of content) {
full += chunk;
@@ -320,6 +346,23 @@ export class TelegramChannel extends BaseChannel {
return full;
}
+ async sendToolFeedback(toolName: string, args: Record<string, any>, targetId?: string): Promise<void> {
+ const key = targetId || 'notification';
+ this.stepCounters.set(key, (this.stepCounters.get(key) || 0) + 1);
+ const step = this.stepCounters.get(key)!;
+ const label = formatToolStep(toolName, args);
+ await this.updateStatusMessage(`**Step ${step}.** ${label}`, targetId);
+ }
+
+ async sendStepDone(toolName: string, result: unknown, targetId?: string): Promise<void> {
+ const key = targetId || 'notification';
+ const step = this.stepCounters.get(key) || 0;
+ const summary = formatToolResult(toolName, result);
+ const current = this.statusText.get(key) || '';
+ const line = summary ? `✓ ${summary}` : '✓ done';
+ await this.updateStatusMessage(`${current}\n${line}`, targetId);
+ }
+
async typing(targetId?: string): Promise<void> {
const chatIds = this.resolveTargetChatIds(targetId);
if (chatIds.length === 0 || !this.bot) return;
@@ -890,6 +933,60 @@ export class TelegramChannel extends BaseChannel {
.replace(/&amp;/g, '&');
}
+ private async updateStatusMessage(text: string, targetId?: string): Promise<void> {
+ const chatIds = this.resolveTargetChatIds(targetId);
+ if (chatIds.length === 0 || !this.bot) return;
+
+ const key = targetId || 'notification';
+ this.statusText.set(key, text);
+ const html = mdToTelegram(text);
+
+ for (const chatId of chatIds) {
+ const existingMsgId = this.statusMessageIds.get(key);
+ if (existingMsgId) {
+ try {
+ await this.bot.api.editMessageText(chatId, existingMsgId, html, { parse_mode: 'HTML' });
+ return;
+ } catch {
+ this.statusMessageIds.delete(key);
+ }
+ }
+
+ try {
+ const msg = await this.bot.api.sendMessage(chatId, html, { parse_mode: 'HTML' });
+ this.statusMessageIds.set(key, msg.message_id);
+ } catch {
+ try {
+ const msg = await this.bot.api.sendMessage(chatId, this.stripHtml(html));
+ this.statusMessageIds.set(key, msg.message_id);
+ } catch {
+ logger.warn({ chatId }, 'Failed to send status message');
+ }
+ }
+ }
+ }
+
+ private async deleteStatusMessage(targetId?: string): Promise<void> {
+ const key = targetId || 'notification';
+ const msgId = this.statusMessageIds.get(key);
+ if (msgId && this.bot) {
+ const chatIds = this.resolveTargetChatIds(targetId);
+ for (const chatId of chatIds) {
+ await this.bot.api.deleteMessage(chatId, msgId).catch(() => {});
+ }
+ this.statusMessageIds.delete(key);
+ this.statusText.delete(key);
+ this.stepCounters.delete(key);
+ }
+ }
+
+ resetStepCounter(targetId?: string): void {
+ const key = targetId || 'notification';
+ this.stepCounters.delete(key);
+ this.statusText.delete(key);
+ this.deleteStatusMessage(targetId);
+ }
+
private isImageFile(ext: string): boolean {
return ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.svg'].includes(ext);
}
diff --git a/src/core/agent.ts b/src/core/agent.ts
index 887e3cf5..18d6e443 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -13,6 +13,7 @@ import { Lifecycle } from './lifecycle.js';
import { Scheduler } from './scheduler.js';
import { logger } from '../utils/logger.js';
import { CLIChannel } from '../channels/cli.js';
+import { TelegramChannel } from '../channels/telegram.js';
import { formatToolStep } from '../utils/tool-label.js';
import type { ArrowSelectOption } from '../utils/arrow-select.js';
import {
@@ -393,6 +394,11 @@ export class Agent {
const canStream = msg.channelType === 'cli' || (msg.channelType === 'telegram' && this.telegramStreaming);
+ const tgChannel = this.channels.get('telegram');
+ if (msg.channelType === 'telegram' && tgChannel) {
+ (tgChannel as TelegramChannel).resetStepCounter(msg.channelId);
+ }
+
for (const provider of fallbackIterator) {
try {
logger.info({ provider: provider.name, model: provider.getModel(), steps: MAX_STEPS, stream: canStream }, 'Generating agentic response');
@@ -466,6 +472,20 @@ export class Agent {
}
}
}
+ } else if (channel instanceof TelegramChannel) {
+ const tgCh = channel as TelegramChannel;
+ for (const tc of toolCalls) {
+ await tgCh.sendToolFeedback(tc.toolName, tc.args as Record<string, any>, msg.channelId).catch(() => {});
+ }
+ if (toolResults) {
+ for (let i = 0; i < toolResults.length; i++) {
+ const tr = toolResults[i] as any;
+ const tcName = toolCalls[i]?.toolName as string | undefined;
+ if (tcName) {
+ await tgCh.sendStepDone(tcName, tr.result ?? tr, msg.channelId).catch(() => {});
+ }
+ }
+ }
} else {
await channel.send(` [Using: ${names}]`, msg.channelId).catch(() => {});
}
@@ -569,6 +589,20 @@ export class Agent {
}
}
}
+ } else if (channel instanceof TelegramChannel) {
+ const tgCh = channel as TelegramChannel;
+ for (const tc of toolCalls) {
+ await tgCh.sendToolFeedback(tc.toolName, tc.args as Record<string, any>, msg.channelId).catch(() => {});
+ }
+ if (toolResults) {
+ for (let i = 0; i < toolResults.length; i++) {
+ const tr = toolResults[i] as any;
+ const tcName = toolCalls[i]?.toolName as string | undefined;
+ if (tcName) {
+ await tgCh.sendStepDone(tcName, tr.result ?? tr, msg.channelId).catch(() => {});
+ }
+ }
+ }
} else {
await channel.send(` [Using: ${names}]`, msg.channelId).catch(() => {});
}