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.

72.3 KB
Raw Blame
import fs from 'node:fs';
import os from 'node:os';
import { currentSpeechEngine, NO_SPEECH_SERVICE } from '../plugins/speech-choice.js';
import { transcribeFile } from '../plugins/transcribe.js';
import path from 'node:path';
import { Bot, InputFile, InlineKeyboard } from 'grammy';
import { autoRetry } from '@grammyjs/auto-retry';
import type { ChannelMessage } from '../types/channel.js';
import { BaseChannel, type PermissionMode, type ChannelAction } from './base.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';
import { formatToolStep, formatToolResult } from '../utils/tool-label.js';
import { RegistryClient, isValidSkillId, searchFeed, type RegistrySkillSummary } from '../skills/registry.js';
import { SkillStore } from '../skills/store.js';
import { SkillLoader } from '../skills/loader.js';

const MAX_MESSAGE_LENGTH = 4096;
const ACCESS_ACTION_PREFIX = 'tg_access';
const MEMORY_ACTION_PREFIX = 'tg_memory';

type ApprovalResolver = () => void;
type ChoiceResolver = (value: string) => void;

interface ActionTapContext {
  callbackQuery: { data: string; message?: { chat?: { id?: number } } };
  chat?: { id?: number };
  from?: { id?: number; first_name?: string };
  answerCallbackQuery: (args: { text: string }) => Promise<unknown>;
}

export class TelegramChannel extends BaseChannel {
  readonly type = 'telegram' as const;
  private bot: Bot | 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();
  private pendingChoices: Map<string, ChoiceResolver> = new Map();
  private processedMessages = new Map<string, number>();
  private static readonly DEDUP_TTL = 5 * 60_000;
  private static readonly DEDUP_MAX_SIZE = 10_000;
  private dedupCleanupInterval: NodeJS.Timeout | null = null;
  private permissionModes = new Map<number, PermissionMode>();
  private onPermissionMode?: (mode: PermissionMode, chatId: number) => void;
  private statusMessageIds = new Map<string, number>();
  private statusUpdateQueues = new Map<string, Promise<void>>();
  private stepCounters = new Map<string, number>();
  private stepHistory = new Map<string, string[]>();
  private statusText = new Map<string, string>();
  /** Track all ephemeral message IDs (permissions, loops, status) per chat for cleanup */
  private ephemeralMessageIds = new Map<string, number[]>();
  /** Track pinned status message per chat (only one at a time) */
  private pinnedMessageIds = new Map<string, number>();
  /** Minimum steps before we pin the status card */
  private static readonly PIN_STEP_THRESHOLD = 3;
  /** Whether a task is currently active per chat — gates message routing */
  private taskActive = new Map<string, boolean>();
  /** Deferred AI responses to send after task completes */
  private deferredResponses = new Map<string, string>();
  /** Notices appended to the status card during a task (Autopilot warnings, etc.) */
  private statusNotices = new Map<string, string[]>();
  /** Maximum number of notice lines to show in the status card */
  private static readonly MAX_STATUS_NOTICES = 3;
  /** Maximum number of notice lines retained per task (heartbeats arrive every 20-60s) */
  private static readonly MAX_STORED_STATUS_NOTICES = 8;
  /** How long an inline-keyboard prompt waits before answering for the user */
  private static readonly PROMPT_TIMEOUT_MS = 120_000;
  /** Sent prompt cards (permission / choice / continue), keyed by prompt id, so the outcome can be written back in place */
  private promptCards = new Map<string, { chatId: number; messageId: number; html: string }>();

  constructor(private config: MercuryConfig) {
    super();
  }

  setChatCommandContext(ctx: import('../capabilities/registry.js').ChatCommandContext): void {
    this.chatCommandContext = ctx;
  }

  /** Mark a task as active — routes send() through the status card */
  beginTask(targetId?: string): void {
    const key = targetId || 'notification';
    this.taskActive.set(key, true);
    this.deferredResponses.delete(key);
    this.statusNotices.delete(key);
  }

  /** Mark task as ended — allows normal send() again */
  endTask(targetId?: string): void {
    const key = targetId || 'notification';
    this.taskActive.set(key, false);
  }

  /** Check if a task is currently active */
  isTaskActive(targetId?: string): boolean {
    const key = targetId || 'notification';
    return this.taskActive.get(key) ?? false;
  }

  /** Peek at deferred response text. A successful final send clears it. */
  popDeferredResponse(targetId?: string): string | undefined {
    const key = targetId || 'notification';
    return this.deferredResponses.get(key);
  }

  /** Explicitly queue the final AI response to send after progress cleanup. */
  deferResponse(targetId: string | undefined, content: string): void {
    const key = targetId || 'notification';
    if (content.trim()) {
      this.deferredResponses.set(key, content);
    }
  }

  setOnPermissionMode(handler: (mode: PermissionMode, chatId: number) => void): void {
    this.onPermissionMode = handler;
  }

  getPermissionMode(chatId: number): PermissionMode {
    return this.permissionModes.get(chatId) ?? 'ask-me';
  }

  async start(): Promise<void> {
    if (this.bot) return; // Already started — don't create a second polling instance

    const token = this.config.channels.telegram.botToken;
    if (!token) {
      logger.warn('Telegram bot token not set — skipping');
      return;
    }

    const bot = new Bot(token);
    bot.api.config.use(autoRetry());

    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;

      const dedupKey = `${chatId}:${ctx.message.message_id}`;
      if (this.processedMessages.has(dedupKey)) {
        logger.debug({ chatId, messageId: ctx.message.message_id }, 'Telegram: dedup skipping message');
        return;
      }
      this.processedMessages.set(dedupKey, Date.now());
      if (this.processedMessages.size > TelegramChannel.DEDUP_MAX_SIZE) {
        this.cleanupDedup();
      }

      if (ctx.chat.type !== 'private') {
        await this.sendDirectMessage(chatId, 'This bot is only available in private one-to-one chats.');
        return;
      }

      if (command === '/start' || command === '/pair') {
        await this.handleAccessRequest(userId, chatId, username, firstName);
        return;
      }

      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;
      }

      if (command === '/memory') {
        if (!this.chatCommandContext) {
          await this.sendDirectMessage(chatId, 'Memory not available.');
          return;
        }
        await this.sendMemoryKeyboard(chatId);
        return;
      }

      this.lastActiveChatId = chatId;
      logger.info({ chatId, text: ctx.message.text?.slice(0, 50) }, 'Telegram message received');

      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((e: any) => logger.warn({ e }, 'telegram permission ask failed'));
        this.permissionModes.set(chatId, 'ask-me');
      }

      if (command === '/unpair') {
        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;
      }

      if (command === '/skills') {
        await this.handleSkillsCommand(chatId, userId, text);
        return;
      }

      if (command === '/permissions') {
        this.askPermissionMode(`telegram:${chatId}`).then((mode) => {
          this.permissionModes.set(chatId, mode);
          if (this.onPermissionMode) {
            this.onPermissionMode(mode, chatId);
          }
        }).catch((e: any) => logger.warn({ e }, 'telegram permission ask failed'));
        return;
      }

      const msg: ChannelMessage = {
        id: ctx.message.message_id.toString(),
        channelId: `telegram:${chatId}`,
        channelType: 'telegram',
        senderId: ctx.from?.id.toString() ?? 'unknown',
        senderName: ctx.from?.first_name,
        senderRole: this.isAdminUser(userId) ? 'admin' : 'member',
        content: ctx.message.text,
        timestamp: ctx.message.date * 1000,
        metadata: { chatId, messageId: ctx.message.message_id },
      };
      this.emit(msg);
    });

    // Voice notes and audio messages: heard (transcribed), then handled like text.
    bot.on(['message:voice', 'message:audio'], async (ctx) => {
      const chatId = ctx.chat.id;
      const userId = ctx.from?.id;
      if (!userId || ctx.chat.type !== 'private') return;
      const dedupKey = `${chatId}:${ctx.message.message_id}`;
      if (this.processedMessages.has(dedupKey)) return;
      this.processedMessages.set(dedupKey, Date.now());
      if (!findTelegramApprovedUser(this.config, userId)) {
        await this.sendDirectMessage(chatId, 'This bot is not available to you. Send /start to request access.');
        return;
      }
      const media = ctx.message.voice ?? ctx.message.audio;
      if (!media) return;
      if ((media.file_size ?? 0) > 20 * 1024 * 1024) {
        await this.sendDirectMessage(chatId, '🎤 That recording is too long for me to fetch (Telegram lets bots download up to 20 MB). Could you send a shorter one, or type it?');
        return;
      }
      const engine = currentSpeechEngine('listen');
      if (!engine) {
        await this.sendDirectMessage(chatId, `🎤 I can't listen to voice notes yet: that needs ${NO_SPEECH_SERVICE} Meanwhile, please type it.`);
        return;
      }
      const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mercury-tg-voice-'));
      let said = '';
      try {
        const file = await ctx.api.getFile(media.file_id);
        if (!file.file_path) throw new Error('Telegram gave no file');
        const res = await fetch(`https://api.telegram.org/file/bot${bot.token}/${file.file_path}`);
        if (!res.ok) throw new Error(`download failed (${res.status})`);
        const local = path.join(dir, `voice${path.extname(file.file_path) || '.ogg'}`);
        fs.writeFileSync(local, Buffer.from(await res.arrayBuffer()));
        said = (await transcribeFile(local, engine)).trim();
      } catch (err) {
        await this.sendDirectMessage(chatId, `🎤 I couldn't understand that voice note (${(err as Error).message.slice(0, 160)}). Could you type it?`);
        return;
      } finally {
        fs.rmSync(dir, { recursive: true, force: true });
      }
      if (!said) {
        await this.sendDirectMessage(chatId, "🎤 I couldn't hear any words in that. Could you try again, or type it?");
        return;
      }
      this.lastActiveChatId = chatId;
      const caption = ctx.message.caption?.trim();
      this.emit({
        id: ctx.message.message_id.toString(),
        channelId: `telegram:${chatId}`,
        channelType: 'telegram',
        senderId: userId.toString(),
        senderName: ctx.from?.first_name,
        senderRole: this.isAdminUser(userId) ? 'admin' : 'member',
        content: caption ? `${caption}\n${said}` : said,
        timestamp: ctx.message.date * 1000,
        // voiceNote: a reply can come back as a voice note (/media replies).
        metadata: { chatId, messageId: ctx.message.message_id, voiceNote: true },
      });
    });

    bot.on('callback_query:data', (ctx) => this.handleCallbackQuery(ctx));

    bot.catch((err) => {
      logger.error({ err: err.message }, 'Telegram bot error');
    });

    this.bot = bot;

    this.dedupCleanupInterval = setInterval(() => this.cleanupDedup(), 30_000);

    // Start long-polling in the background.
    // bot.start() blocks until the first getUpdates succeeds, which can take
    // 30-40s on slow networks. Don't block Mercury startup — let it connect
    // asynchronously. The guard on line 105 (if this.bot) prevents duplicate instances.
    void bot.start({
      onStart: async (info) => {
        logger.info({ bot: info.username }, 'Telegram bot started — long polling active');
        this.ready = true;
        await this.registerCommands();
      },
    }).catch((err: any) => {
      const message = err?.description || err?.message || String(err);
      logger.error({ err: message }, 'Telegram bot polling stopped');
      if (this.bot === bot) {
        this.bot = null;
        this.ready = false;
        if (this.dedupCleanupInterval) {
          clearInterval(this.dedupCleanupInterval);
          this.dedupCleanupInterval = null;
        }
      }
    });
  }

  private async registerCommands(): Promise<void> {
    if (!this.bot) return;

    const commands = [
      { command: 'start', description: 'Request Telegram access to this Mercury instance' },
      { command: 'help', description: 'Show available commands' },
      { command: 'status', description: 'Show agent config, budget, and uptime' },
      { command: 'progress', description: 'Live status for the current task' },
      { command: 'stop', description: 'Stop all agents and clear queue' },
      { command: 'budget', description: 'Token budget status and management' },
      { command: 'saver', description: 'Toggle Token Saver Mode (save tokens, terser responses)' },
      { 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: 'models', description: 'List providers or switch AI model' },
      { command: 'image', description: 'Make an image: /image <what to draw>' },
      { command: 'media', description: 'Image and speech models, voice replies' },
      { command: 'say', description: 'Say it as a voice note: /say <text>' },
      { command: 'video', description: 'Make a short video: /video <the shot>' },
      { command: 'music', description: 'Make a song: /music <style, mood, lyrics>' },
      { command: 'code', description: 'Programming mode (plan / execute / off)' },
      { command: 'agents', description: 'List and manage sub-agents' },
      { command: 'bots', description: 'Your bots: roster with controls, cost, outputs, stop/start' },
      { command: 'bot', description: 'Message a bot: /bot <id> <task>' },
      { command: 'bg', description: 'Background tasks (list / cancel / run)' },
      { command: 'spotify', description: 'Spotify playback controls' },
      { command: 'skills', description: 'Browse and install skills from the registry' },
      { command: 'plugins', description: 'Install, enable, disable and remove plugins' },
      { command: 'unpair', description: 'Reset all Telegram access (admin only)' },
      { command: 'new', description: 'Start a fresh conversation (memory is kept)' },
    ];

    try {
      await this.bot.api.setMyCommands(commands);
      logger.info({ count: commands.length }, 'Telegram bot commands registered');
    } catch (err: any) {
      logger.warn({ err: err.message }, 'Failed to register Telegram commands (non-critical)');
    }
  }

  async stop(): Promise<void> {
    this.bot?.stop();
    this.bot = null;
    this.ready = false;
    this.stopTypingLoop();
    if (this.dedupCleanupInterval) {
      clearInterval(this.dedupCleanupInterval);
      this.dedupCleanupInterval = null;
    }
  }

  async send(content: string, targetId?: string, elapsedMs?: number): Promise<void> {
    const chatIds = this.resolveTargetChatIds(targetId);
    if (chatIds.length === 0 || !this.bot) {
      throw new Error(`Telegram send failed: no valid chat for ${targetId || 'notification'}`);
    }

    const key = targetId || 'notification';

    // During an active task, route messages through the status card instead of creating new messages
    if (this.taskActive.get(key)) {
      const timeSuffix = elapsedMs != null ? ` (${(elapsedMs / 1000).toFixed(1)}s)` : '';
      const fullContent = content + timeSuffix;
      if (!fullContent.trim()) return;

      // If this looks like a final AI response (long, not a system notice), defer it
      const isSystemNotice = content.startsWith('☿ ') || content.startsWith('⚠') || content.startsWith('  [') || content.length < 200;
      if (isSystemNotice) {
        // Append as a notice line in the status card
        const notices = this.statusNotices.get(key) || [];
        // Truncate long notices to keep status card compact
        const truncated = fullContent.length > 80 ? fullContent.slice(0, 77) + '…' : fullContent;
        notices.push(truncated);
        this.statusNotices.set(key, notices);
        // Refresh the status card to include the notice
        await this.refreshStatusCard(targetId);
      } else {
        // Defer the full response — will be sent after task completes
        this.deferredResponses.set(key, fullContent);
      }
      return;
    }

    const timeSuffix = elapsedMs != null ? `\n⏱ ${(elapsedMs / 1000).toFixed(1)}s` : '';
    const fullContent = content + timeSuffix;
    if (!fullContent.trim()) {
      logger.info({ targetId }, 'Telegram send: skipping empty message');
      return;
    }
    const html = mdToTelegram(fullContent);
    const chunks = this.splitMessage(html, MAX_MESSAGE_LENGTH);

    for (const chatId of chatIds) {
      for (const chunk of chunks) {
        try {
          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');
            throw err2;
          }
        }
      }
    }
    if (this.deferredResponses.get(key) === content) {
      this.deferredResponses.delete(key);
    }
  }

  async sendFile(filePath: string, targetId?: string): Promise<void> {
    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)) {
      for (const chatId of chatIds) {
        await this.bot.api.sendMessage(chatId, `File not found: ${filePath}`).catch((e: any) => logger.warn({ e }, "telegram send failed"));
      }
      return;
    }

    const filename = path.basename(resolved);
    const ext = path.extname(resolved).toLowerCase();

    for (const chatId of chatIds) {
      const inputFile = new InputFile(resolved);

      try {
        // Telegram takes photos up to 10 MB as JPEG/PNG/WebP; anything else goes as a file.
        if (this.isImageFile(ext) && fs.statSync(resolved).size <= 10 * 1024 * 1024) {
          await this.bot.api.sendPhoto(chatId, inputFile, { caption: filename });
        } else if (ext === '.gif') {
          await this.bot.api.sendAnimation(chatId, inputFile, { caption: filename });
        } else if (['.ogg', '.oga', '.opus'].includes(ext)) {
          // Ogg/Opus plays as a voice note; anything Telegram won't take as one goes as audio.
          try {
            await this.bot.api.sendVoice(chatId, inputFile);
          } catch {
            await this.bot.api.sendAudio(chatId, new InputFile(resolved), { title: 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((e: any) => logger.warn({ e }, "telegram send failed"));
      }
    }
  }

  async stream(content: AsyncIterable<string>, targetId?: string): Promise<string> {
    const chatIds = this.resolveTargetChatIds(targetId);
    if (chatIds.length === 0 || !this.bot) return '';

    let full = '';
    for await (const chunk of content) {
      full += chunk;
    }

    const key = targetId || 'notification';
    // During an active task, defer the streamed response
    if (this.taskActive.get(key)) {
      this.deferredResponses.set(key, full);
      return full;
    }

    this.deleteStatusMessage(targetId);

    const html = mdToTelegram(full);
    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((e: any) => logger.warn({ e }, "telegram html send failed"));
      }
    }
    return full;
  }

  async sendToolFeedback(toolName: string, args: Record<string, any>, targetId?: string): Promise<void> {
    const key = targetId || 'notification';
    const step = (this.stepCounters.get(key) || 0) + 1;
    this.stepCounters.set(key, step);
    const label = formatToolStep(toolName, args);

    // Build a rolling progress view: completed steps + current
    const history = this.stepHistory.get(key) || [];
    // Keep last 5 completed steps visible
    const recentHistory = history.slice(-5);
    const lines = [
      `⚙️ **Mercury working** (step ${step})`,
      '',
      ...recentHistory.map(h => `✅ ${h}`),
      `⏳ ${label}…`,
    ];
    await this.updateStatusMessage(lines.join('\n'), targetId);

    // Pin the status card once we hit the threshold (substantial task)
    if (step === TelegramChannel.PIN_STEP_THRESHOLD) {
      await this.pinStatusMessage(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 label = formatToolStep(toolName, {} as any);
    const doneLine = summary ? `${label} · ${summary}` : label;

    // Add to history
    const history = this.stepHistory.get(key) || [];
    history.push(doneLine);
    this.stepHistory.set(key, history);

    // Update progress view
    const recentHistory = history.slice(-5);
    const lines = [
      `⚙️ **Mercury working** (${step} steps done)`,
      '',
      ...recentHistory.map(h => `✅ ${h}`),
    ];
    await this.updateStatusMessage(lines.join('\n'), targetId);
  }

  async typing(targetId?: string): Promise<void> {
    const chatIds = this.resolveTargetChatIds(targetId);
    if (chatIds.length === 0 || !this.bot) return;
    await this.bot.api.sendChatAction(chatIds[0], 'typing');
  }

  startTypingLoop(chatId: number): void {
    this.stopTypingLoop();
    this.bot?.api.sendChatAction(chatId, 'typing').catch((e: any) => logger.warn({ e }, "telegram sendChatAction failed"));
    this.typingInterval = setInterval(() => {
      this.bot?.api.sendChatAction(chatId, 'typing').catch((e: any) => logger.warn({ e }, "telegram sendChatAction failed"));
    }, 4000);
  }

  stopTypingLoop(): void {
    if (this.typingInterval) {
      clearInterval(this.typingInterval);
      this.typingInterval = null;
    }
  }

  async sendStreamToChat(chatId: number, textStream: AsyncIterable<string>): Promise<string> {
    if (!this.bot) return '';

    // During an active task, collect the stream and defer it
    // Check all task-active keys since we have chatId not targetId
    const activeKey = this.findActiveTaskKey(chatId);
    if (activeKey) {
      this.startTypingLoop(chatId);
      try {
        let full = '';
        for await (const chunk of textStream) {
          full += chunk;
        }
        this.deferredResponses.set(activeKey, full);
        return full;
      } finally {
        this.stopTypingLoop();
      }
    }

    const STREAM_EDIT_INTERVAL = 1500;
    const STREAM_MIN_LENGTH = 20;

    this.startTypingLoop(chatId);

    try {
      let full = '';
      let messageId: number | null = null;
      let lastEditTime = 0;
      let lastEditLength = 0;

      for await (const chunk of textStream) {
        full += chunk;

        const now = Date.now();
        const timeSinceLastEdit = now - lastEditTime;
        const charsSinceLastEdit = full.length - lastEditLength;

        if (messageId === null && full.length >= STREAM_MIN_LENGTH) {
          try {
            const msg = await this.bot.api.sendMessage(chatId, this.escapeHtml(full) + ' ▌', { parse_mode: 'HTML' });
            messageId = msg.message_id;
            lastEditTime = now;
            lastEditLength = full.length;
          } catch {
            messageId = null;
          }
        } else if (messageId !== null && timeSinceLastEdit >= STREAM_EDIT_INTERVAL && charsSinceLastEdit >= 20) {
          try {
            await this.bot.api.editMessageText(chatId, messageId, this.escapeHtml(full) + ' ▌', { parse_mode: 'HTML' });
            lastEditTime = now;
            lastEditLength = full.length;
          } catch {
            // edit failed — rate limited or message unchanged, skip
          }
        }
      }

      if (messageId !== null) {
        const html = mdToTelegram(full);
        try {
          await this.bot.api.editMessageText(chatId, messageId, html, { parse_mode: 'HTML' });
        } catch {
          try {
            await this.bot.api.editMessageText(chatId, messageId, this.stripHtml(html));
          } catch {
            // final edit failed
          }
        }
      } else if (full.trim()) {
        const html = mdToTelegram(full);
        const stripped = this.stripHtml(html);
        try {
          await this.bot.api.sendMessage(chatId, html, { parse_mode: 'HTML' });
        } catch {
          if (stripped.trim()) {
            try {
              await this.bot.api.sendMessage(chatId, stripped);
            } catch {
              // plain text send also failed
            }
          }
        }
      }

      return full;
    } finally {
      this.stopTypingLoop();
    }
  }

  /**
   * Tappable actions (bots control, ADR-023): a message with inline buttons
   * whose taps run slash commands exactly as if the user had typed them —
   * same routing, same permissions, same replies. Commands are kept behind
   * short tokens (callback data is capped at 64 bytes) in a bounded map.
   */
  private readonly actionTokens = new Map<string, string>();
  private static readonly ACTION_TOKENS_MAX = 300;

  async sendWithActions(content: string, rows: ChannelAction[][], targetId?: string): Promise<void> {
    const chatIds = this.resolveTargetChatIds(targetId);
    const chatId = chatIds[0];
    if (!chatId || !this.bot) {
      await this.send(content, targetId);
      return;
    }
    const keyboard = new InlineKeyboard();
    rows.forEach((row, i) => {
      for (const button of row) {
        const token = Math.random().toString(36).slice(2, 10);
        this.actionTokens.set(token, button.command);
        keyboard.text(button.label.slice(0, 40), `ba:${token}`);
      }
      if (i < rows.length - 1) keyboard.row();
    });
    while (this.actionTokens.size > TelegramChannel.ACTION_TOKENS_MAX) {
      const oldest = this.actionTokens.keys().next().value;
      if (oldest === undefined) break;
      this.actionTokens.delete(oldest);
    }
    const html = mdToTelegram(content);
    try {
      await this.bot.api.sendMessage(chatId, html, { parse_mode: 'HTML', reply_markup: keyboard });
    } catch {
      await this.bot.api.sendMessage(chatId, this.stripHtml(html), { reply_markup: keyboard }).catch((e: unknown) => logger.warn({ e }, 'telegram actions send failed'));
    }
  }

  /** Inline-keyboard taps (approvals, choices, access/memory admin actions). */
  private async handleCallbackQuery(ctx: any): Promise<void> {
    const data: string = ctx.callbackQuery.data;
    if (data.startsWith('ba:')) {
      await this.handleActionTap(ctx, data.slice(3));
      return;
    }
    if (data.startsWith(`${ACCESS_ACTION_PREFIX}:`)) {
      await this.handleAccessCallback(ctx, data);
      return;
    }

    if (data.startsWith(`${MEMORY_ACTION_PREFIX}:`)) {
      await this.handleMemoryCallback(ctx, data);
      return;
    }

    if (data.startsWith('choice:')) {
      const [, id, value] = data.split(':');
      const resolver = id ? this.pendingChoices.get(id) : undefined;
      if (!resolver) {
        await ctx.answerCallbackQuery({ text: 'Expired' });
        return;
      }

      this.pendingChoices.delete(id);
      // The resolver settles the card: outcome appended, keyboard removed.
      resolver(value ?? '');
      await ctx.answerCallbackQuery({ text: 'Selected' });
      return;
    }

    const resolver = this.pendingApprovals.get(data);
    if (!resolver) {
      await ctx.answerCallbackQuery({ text: 'Expired' });
      return;
    }

    this.pendingApprovals.delete(data);
    // The resolver settles the card: outcome appended, keyboard removed (#23).
    resolver();
    const action = data.slice(data.lastIndexOf(':') + 1);
    await ctx.answerCallbackQuery({ text: action === 'no' ? 'Denied' : 'Approved' });
  }

  /** A tapped action runs its slash command as a message from the tapping user. */
  // (the grammy context fields the handler reads; the rest is irrelevant here)
  private async handleActionTap(ctx: ActionTapContext, token: string): Promise<void> {
    const command = this.actionTokens.get(token);
    const userId: number | undefined = ctx.from?.id;
    const chatId: number | undefined = ctx.callbackQuery?.message?.chat?.id ?? ctx.chat?.id;
    if (!command || !chatId) {
      await ctx.answerCallbackQuery({ text: 'Expired — send /bots again' }).catch(() => {});
      return;
    }
    if (!userId || !findTelegramApprovedUser(this.config, userId)) {
      await ctx.answerCallbackQuery({ text: 'Not allowed' }).catch(() => {});
      return;
    }
    await ctx.answerCallbackQuery({ text: command.slice(0, 60) }).catch(() => {});
    this.emit({
      id: `tap-${Date.now().toString(36)}-${token}`,
      channelId: `telegram:${chatId}`,
      channelType: 'telegram',
      senderId: String(userId),
      senderName: ctx.from?.first_name,
      senderRole: this.isAdminUser(userId) ? 'admin' : 'member',
      content: command,
      timestamp: Date.now(),
      metadata: { chatId, tapped: true },
    });
  }

  /**
   * Send a prompt card with an inline keyboard. Returns the message id (or
   * undefined when sending failed) and remembers the card so the outcome can be
   * written back into it later.
   */
  private async sendPromptCard(id: string, chatId: number, targetId: string | undefined, html: string, keyboard: InlineKeyboard): Promise<number | undefined> {
    if (!this.bot) return undefined;
    let sentMsgId: number | undefined;
    try {
      const msg = await this.bot.api.sendMessage(chatId, html, { parse_mode: 'HTML', reply_markup: keyboard });
      sentMsgId = msg.message_id;
    } catch {
      const msg = await this.bot.api.sendMessage(chatId, this.stripHtml(html), { reply_markup: keyboard });
      sentMsgId = msg.message_id;
    }
    if (sentMsgId) {
      this.trackEphemeral(targetId, sentMsgId);
      this.promptCards.set(id, { chatId, messageId: sentMsgId, html });
    }
    return sentMsgId;
  }

  /**
   * Write the outcome of a prompt into its card: the inline keyboard is removed
   * and `outcomeHtml` is appended below the original question. The card stays
   * in the chat (it is still ephemeral — cleaned up when the task completes) so
   * the user can see what was decided, including decisions made FOR them on
   * timeout.
   */
  private async settlePromptCard(id: string, outcomeHtml: string): Promise<void> {
    const card = this.promptCards.get(id);
    this.promptCards.delete(id);
    if (!card || !this.bot) return;
    const html = `${card.html}\n\n${outcomeHtml}`;
    try {
      await this.bot.api.editMessageText(card.chatId, card.messageId, html, { parse_mode: 'HTML' });
    } catch (err: any) {
      const description = String(err?.description || err?.message || '');
      if (description.includes('message is not modified')) return;
      await this.bot.api.editMessageText(card.chatId, card.messageId, this.stripHtml(html))
        .catch((e: any) => logger.debug({ e }, 'telegram settlePromptCard failed'));
    }
  }

  private static timeoutOutcome(decision: string): string {
    return `⏱ No answer in 2 min — ${decision}`;
  }

  async askPermission(prompt: string, targetId?: string): Promise<string> {
    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)}`;
    const keyboard = new InlineKeyboard()
      .text('Allow', `${id}:yes`)
      .text('Always', `${id}:always`)
      .text('Deny', `${id}:no`);

    await this.sendPromptCard(id, chatId, targetId, mdToTelegram(prompt), keyboard);

    const outcomes: Record<string, string> = {
      yes: '✅ <b>Allowed</b>',
      always: '✅ <b>Always allowed</b>',
      no: '🚫 <b>Denied</b>',
    };

    return new Promise((resolve) => {
      const actions = Object.keys(outcomes);
      const settle = (result: string, outcomeHtml: string) => {
        clearTimeout(timer);
        for (const action of actions) this.pendingApprovals.delete(`${id}:${action}`);
        void this.settlePromptCard(id, outcomeHtml);
        resolve(result);
      };
      for (const action of actions) {
        this.pendingApprovals.set(`${id}:${action}`, () => settle(action, outcomes[action]));
      }
      const timer = setTimeout(
        () => settle('no', TelegramChannel.timeoutOutcome('treated as <b>Deny</b>')),
        TelegramChannel.PROMPT_TIMEOUT_MS,
      );
    });
  }

  async presentChoicePrompt(question: string, options: Array<{ value: string; label: string }>, targetId?: string): Promise<string> {
    const chatIds = this.resolveTargetChatIds(targetId);
    const chatId = chatIds[0];
    if (!chatId || !this.bot) return options[0]?.value || '';

    const id = `choice_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
    const keyboard = new InlineKeyboard();
    for (let i = 0; i < options.length; i++) {
      const option = options[i];
      keyboard.text(option.label.slice(0, 60), `choice:${id}:${option.value}`);
      if (i < options.length - 1 && (i + 1) % 2 === 0) {
        keyboard.row();
      }
    }

    await this.sendPromptCard(id, chatId, targetId, mdToTelegram(question), keyboard);

    const labelFor = (value: string) => this.escapeHtml(options.find(o => o.value === value)?.label || value);

    return new Promise((resolve) => {
      const settle = (value: string, outcomeHtml: string) => {
        clearTimeout(timer);
        this.pendingChoices.delete(id);
        void this.settlePromptCard(id, outcomeHtml);
        resolve(value);
      };
      this.pendingChoices.set(id, (value) => settle(value, `✅ Selected: <b>${labelFor(value)}</b>`));
      const timer = setTimeout(() => {
        if (!this.pendingChoices.has(id)) return;
        const fallback = options[0]?.value || '';
        settle(fallback, TelegramChannel.timeoutOutcome(`continued with the recommended option: <b>${labelFor(fallback)}</b>`));
      }, TelegramChannel.PROMPT_TIMEOUT_MS);
    });
  }

  async askToContinue(question: string, targetId?: string): Promise<boolean> {
    const chatIds = this.resolveTargetChatIds(targetId);
    const chatId = chatIds[0];
    if (!chatId || !this.bot) return false;

    const id = `loop_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
    const keyboard = new InlineKeyboard()
      .text('Continue', `${id}:yes`)
      .text('Stop', `${id}:no`);

    await this.sendPromptCard(id, chatId, targetId, mdToTelegram(question), keyboard);

    return new Promise((resolve) => {
      const settle = (result: boolean, outcomeHtml: string) => {
        clearTimeout(timer);
        this.pendingApprovals.delete(`${id}:yes`);
        this.pendingApprovals.delete(`${id}:no`);
        void this.settlePromptCard(id, outcomeHtml);
        resolve(result);
      };
      this.pendingApprovals.set(`${id}:yes`, () => settle(true, '▶️ <b>Continuing</b>'));
      this.pendingApprovals.set(`${id}:no`, () => settle(false, '⏹ <b>Stopped</b>'));
      const timer = setTimeout(
        () => settle(false, TelegramChannel.timeoutOutcome('<b>stopped</b>')),
        TelegramChannel.PROMPT_TIMEOUT_MS,
      );
    });
  }

  async askPermissionMode(targetId?: string): Promise<PermissionMode> {
    const chatIds = this.resolveTargetChatIds(targetId);
    const chatId = chatIds[0];
    if (!chatId || !this.bot) return 'ask-me';

    const id = `perm_mode_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
    const keyboard = new InlineKeyboard()
      .text('🔒 Ask Me', `${id}:ask-me`)
      .text('✅ Allow All', `${id}:allow-all`);

    const html = `<b>Permission Mode</b>\nHow should Mercury handle risky actions this session?\n\n🔒 <b>Ask Me</b> — confirm before file writes, commands, and scope changes\n✅ <b>Allow All</b> — auto-approve everything (scopes, commands, loops)`;

    await this.sendPromptCard(id, chatId, targetId, html, keyboard);

    return new Promise((resolve) => {
      const settle = (result: PermissionMode, outcomeHtml: string) => {
        clearTimeout(timer);
        this.pendingApprovals.delete(`${id}:ask-me`);
        this.pendingApprovals.delete(`${id}:allow-all`);
        void this.settlePromptCard(id, outcomeHtml);
        resolve(result);
      };
      this.pendingApprovals.set(`${id}:ask-me`, () => settle('ask-me', '🔒 <b>Ask Me</b> selected'));
      this.pendingApprovals.set(`${id}:allow-all`, () => settle('allow-all', '✅ <b>Allow All</b> selected'));
      const timer = setTimeout(
        () => settle('ask-me', TelegramChannel.timeoutOutcome('defaulting to <b>Ask Me</b>')),
        TelegramChannel.PROMPT_TIMEOUT_MS,
      );
    });
  }

  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((e: any) => logger.warn({ e }, "telegram send failed"));
      }
    }
  }

  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((e: any) => logger.debug({ e }, "telegram editMessageReplyMarkup failed"));
      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((e: any) => logger.debug({ e }, "telegram editMessageReplyMarkup failed"));
      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((e: any) => logger.debug({ e }, "telegram editMessageReplyMarkup failed"));
      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 async sendMemoryKeyboard(chatId: number): Promise<void> {
    if (!this.bot || !this.chatCommandContext) return;

    const summary = this.chatCommandContext.memorySummary();
    const lines = [
      `<b>Memory Overview</b>`,
      `Conscious memories: ${summary.total}`,
      `Subconscious memories: ${summary.subconsciousTotal}`,
      `Learning: ${summary.learningPaused ? '⏸ PAUSED' : '✅ ACTIVE'}`,
    ];
    if (summary.profileSummary) {
      lines.push(`\n<i>Profile: ${this.escapeHtml(summary.profileSummary)}</i>`);
    }
    const typeEntries = Object.entries(summary.byType);
    if (typeEntries.length > 0) {
      lines.push('\n<b>By type:</b>');
      for (const [type, count] of typeEntries) {
        lines.push(`  ${type}: ${count}`);
      }
    }

    const learningLabel = summary.learningPaused ? '▶ Resume' : '⏸ Pause';
    const keyboard = new InlineKeyboard()
      .text('📋 Overview', `${MEMORY_ACTION_PREFIX}:overview`)
      .text('🔍 Recent', `${MEMORY_ACTION_PREFIX}:recent`)
      .row()
      .text('💤 Subconscious', `${MEMORY_ACTION_PREFIX}:subconscious`)
      .text(learningLabel, `${MEMORY_ACTION_PREFIX}:toggle_learning`)
      .row()
      .text('🗑 Clear All', `${MEMORY_ACTION_PREFIX}:clear_confirm`)
      .row()
      .text('🧠 Shared', `${MEMORY_ACTION_PREFIX}:shared`);

    await this.bot.api.sendMessage(chatId, lines.join('\n'), {
      parse_mode: 'HTML',
      reply_markup: keyboard,
    }).catch(async () => {
      await this.bot!.api.sendMessage(chatId, lines.join('\n'), { reply_markup: keyboard });
    });
  }

  private async handleMemoryCallback(ctx: any, data: string): Promise<void> {
    if (!this.bot || !this.chatCommandContext) {
      await ctx.answerCallbackQuery({ text: 'Not available' });
      return;
    }

    const action = data.slice(`${MEMORY_ACTION_PREFIX}:`.length);
    const chatId = ctx.callbackQuery.message?.chat?.id;
    if (!chatId) {
      await ctx.answerCallbackQuery({ text: 'Error' });
      return;
    }

    if (action === 'overview') {
      await ctx.answerCallbackQuery({ text: 'Overview' });
      const summary = this.chatCommandContext.memorySummary();
      const lines = [
        `<b>Memory Overview</b>`,
        `Conscious memories: ${summary.total}`,
        `Subconscious memories: ${summary.subconsciousTotal}`,
        `Learning: ${summary.learningPaused ? '⏸ PAUSED' : '✅ ACTIVE'}`,
      ];
      if (summary.profileSummary) {
        lines.push(`\n<i>Profile: ${this.escapeHtml(summary.profileSummary)}</i>`);
      }
      if (summary.activeSummary) {
        lines.push(`<i>Active: ${this.escapeHtml(summary.activeSummary)}</i>`);
      }
      const typeEntries = Object.entries(summary.byType);
      if (typeEntries.length > 0) {
        lines.push('\n<b>By type:</b>');
        for (const [type, count] of typeEntries) {
          lines.push(`  ${type}: ${count}`);
        }
      }
      await this.bot.api.sendMessage(chatId, lines.join('\n'), { parse_mode: 'HTML' }).catch(async () => {
        await this.bot!.api.sendMessage(chatId, lines.join('\n'));
      });
      return;
    }

    if (action === 'recent') {
      await ctx.answerCallbackQuery({ text: 'Recent memories' });
      const recent = this.chatCommandContext.memoryRecent(10);
      if (recent.length === 0) {
        await this.bot.api.sendMessage(chatId, 'No memories yet.').catch((e: any) => logger.warn({ e }, "telegram send failed"));
        return;
      }
      const lines = ['<b>Recent Memories:</b>\n'];
      for (const r of recent) {
        const scope = r.scope === 'active' ? '⏳' : r.scope === 'subconscious' ? '💤' : '📌';
        lines.push(`${scope} [${r.type}] ${this.escapeHtml(r.summary)}`);
        lines.push(`   Confidence: ${r.confidence.toFixed(2)} | Evidence: ${r.evidenceKind} | Seen: ${r.evidenceCount}x`);
      }
      await this.bot.api.sendMessage(chatId, lines.join('\n'), { parse_mode: 'HTML' }).catch(async () => {
        await this.bot!.api.sendMessage(chatId, lines.join('\n'));
      });
      return;
    }

    if (action === 'toggle_learning') {
      const currentSummary = this.chatCommandContext.memorySummary();
      const currentlyPaused = currentSummary.learningPaused;
      this.chatCommandContext.memorySetLearningPaused(!currentlyPaused);
      const label = currentlyPaused ? '▶ Learning resumed' : '⏸ Learning paused';
      await ctx.answerCallbackQuery({ text: label });
      await this.bot.api.sendMessage(chatId, currentlyPaused
        ? 'Learning resumed. Mercury will remember new things from conversations.'
        : 'Learning paused. Mercury will not store new memories until resumed.',
      ).catch((e: any) => logger.warn({ e }, "telegram send failed"));
      await this.sendMemoryKeyboard(chatId);
      return;
    }

    if (action === 'clear_confirm') {
      const keyboard = new InlineKeyboard()
        .text('🗑 Yes, clear everything', `${MEMORY_ACTION_PREFIX}:clear_yes`)
        .text('✖ Cancel', `${MEMORY_ACTION_PREFIX}:clear_no`);
      await ctx.answerCallbackQuery({});
      await this.bot.api.sendMessage(chatId, '⚠️ Are you sure you want to clear <b>all</b> memories? This cannot be undone.', {
        parse_mode: 'HTML',
        reply_markup: keyboard,
      }).catch(async () => {
        await this.bot!.api.sendMessage(chatId, '⚠️ Are you sure you want to clear all memories?', { reply_markup: keyboard });
      });
      return;
    }

    if (action === 'clear_yes') {
      const cleared = this.chatCommandContext.memoryClear();
      await ctx.answerCallbackQuery({ text: `Cleared ${cleared} memories` });
      await this.bot.api.sendMessage(chatId, `Cleared ${cleared} memories.`).catch((e: any) => logger.warn({ e }, "telegram send failed"));
      return;
    }

    if (action === 'clear_no') {
      await ctx.answerCallbackQuery({ text: 'Cancelled' });
      return;
    }

    if (action === 'subconscious') {
      if (!this.chatCommandContext) {
        await ctx.answerCallbackQuery({ text: 'Not available' });
        return;
      }
      const subconsciousMemories = this.chatCommandContext.memoryGetSubconscious(5);
      const subconsciousTotal = this.chatCommandContext.memorySummary().subconsciousTotal;
      if (subconsciousMemories.length === 0) {
        await this.bot.api.sendMessage(chatId, '💤 <b>Subconscious Memory</b>\n\nNo subconscious memories yet. Memories move here after 30 days of not being referenced, and are recalled automatically when relevant to a conversation.').catch((e: any) => logger.warn({ e }, "telegram send failed"));
        return;
      }
      const lines = ['💤 <b>Subconscious Memory (first 5 by recency):</b>\n'];
      for (const r of subconsciousMemories) {
        const ageDays = Math.round((Date.now() - r.lastSeenAt) / (1000 * 60 * 60 * 24));
        lines.push(`💤 [${r.type}] ${this.escapeHtml(r.summary)}`);
        lines.push(`   Confidence: ${r.confidence.toFixed(2)} | Last seen: ${ageDays}d ago`);
      }
      if (subconsciousTotal > 5) {
        lines.push(`\n... and ${subconsciousTotal - 5} more subconscious memories stored.`);
      }
      lines.push(`\n<i>These memories can be recalled to conscious when relevant to a conversation.</i>`);
      await this.bot.api.sendMessage(chatId, lines.join('\n'), { parse_mode: 'HTML' }).catch(async () => {
        await this.bot!.api.sendMessage(chatId, lines.join('\n'));
      });
      return;
    }

    if (action === 'shared_back') {
      await this.sendMemoryKeyboard(chatId);
      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 async handleSkillsCommand(chatId: number, userId: number, text: string): Promise<void> {
    const parts = text.trim().split(/\s+/).slice(1);
    const sub = (parts[0] || 'list').toLowerCase();
    const args = parts.slice(1);
    const arg = args.join(' ').trim();

    const registry = new RegistryClient();
    const store = new SkillStore({ registry });
    const loader = new SkillLoader();

    try {
      switch (sub) {
        case 'help':
        case '-h':
        case '--help': {
          await this.sendDirectMessage(
            chatId,
            [
              '*Mercury Skills — Telegram*',
              '',
              '`/skills` — list installed skills',
              '`/skills search <query>` — search the registry',
              '`/skills view <id>` — show details + registry URL',
              '`/skills install <id>` — admin only',
              '`/skills remove <id>` — admin only',
              '',
              'Registry: https://skills.mercuryagent.sh',
            ].join('\n'),
          );
          return;
        }

        case 'list': {
          const installed = loader.getAllSkills();
          if (installed.length === 0) {
            await this.sendDirectMessage(
              chatId,
              'No skills installed.\n\nTry `/skills search <query>` to browse https://skills.mercuryagent.sh.',
            );
            return;
          }
          const lines = installed
            .slice(0, 25)
            .map((s) => `• \`${s.name}\` — ${s.active ? 'active' : 'inactive'}${s.description ? ` — ${s.description}` : ''}`);
          const more = installed.length > 25 ? `\n\n_…and ${installed.length - 25} more. Run \`mercury skills list\` for the full set._` : '';
          await this.sendDirectMessage(
            chatId,
            `*Installed skills (${installed.length})*\n\n${lines.join('\n')}${more}`,
          );
          return;
        }

        case 'search':
        case 'find': {
          if (!arg) {
            await this.sendDirectMessage(chatId, 'Usage: `/skills search <query>`');
            return;
          }
          const feed = await registry.getFeed();
          const scored = searchFeed(feed, arg, 5);
          if (scored.length === 0) {
            await this.sendDirectMessage(chatId, `No results for "${arg}".`);
            return;
          }
          const results = scored.map((s) => s.skill);
          const lines = results.map(
            (r: RegistrySkillSummary) =>
              `• \`${r.id}\` (v${r.version})\n  ${r.description}\n  ${registry.webUrl(r.id)}`,
          );
          await this.sendDirectMessage(
            chatId,
            `*Top ${results.length} matches for "${arg}"*\n\n${lines.join('\n\n')}\n\nReview a skill before installing: \`/skills view <id>\``,
          );
          return;
        }

        case 'view':
        case 'show':
        case 'info': {
          if (!arg) {
            await this.sendDirectMessage(chatId, 'Usage: `/skills view <category/slug>`');
            return;
          }
          if (!isValidSkillId(arg)) {
            await this.sendDirectMessage(chatId, 'Invalid skill id. Expected `<category>/<slug>`.');
            return;
          }
          const detail = await registry.getSkill(arg);
          const tags = detail.tags?.length ? `\n*Tags:* ${detail.tags.join(', ')}` : '';
          const author = detail.author ? `\n*Author:* ${detail.author}` : '';
          await this.sendDirectMessage(
            chatId,
            [
              `*${detail.title}* (\`${detail.id}\`)`,
              `*Version:* ${detail.version}`,
              `*Category:* ${detail.category}`,
              author,
              tags,
              '',
              detail.description,
              '',
              `🔗 ${registry.webUrl(detail.id)}`,
              '',
              this.isAdminUser(userId)
                ? 'Install with: `/skills install ' + detail.id + '`'
                : 'Ask an admin to install: `/skills install ' + detail.id + '`',
            ]
              .filter(Boolean)
              .join('\n'),
          );
          return;
        }

        case 'install':
        case 'add': {
          if (!this.isAdminUser(userId)) {
            await this.sendDirectMessage(chatId, '🔒 Only Telegram admins can install skills.');
            return;
          }
          if (!arg) {
            await this.sendDirectMessage(chatId, 'Usage: `/skills install <category/slug>`');
            return;
          }
          if (!isValidSkillId(arg)) {
            await this.sendDirectMessage(chatId, 'Invalid skill id. Expected `<category>/<slug>`.');
            return;
          }
          await this.sendDirectMessage(chatId, `Installing \`${arg}\`…`);
          const result = await store.install(arg);
          const verb =
            result.status === 'already-installed'
              ? 'Already installed'
              : result.status === 'updated'
                ? 'Updated'
                : result.status === 'reinstalled'
                  ? 'Reinstalled'
                  : 'Installed';
          await this.sendDirectMessage(
            chatId,
            `✅ ${verb} \`${result.id}\` (v${result.version})\n\n🔗 ${registry.webUrl(result.id)}`,
          );
          return;
        }

        case 'remove':
        case 'rm':
        case 'delete':
        case 'uninstall': {
          if (!this.isAdminUser(userId)) {
            await this.sendDirectMessage(chatId, '🔒 Only Telegram admins can remove skills.');
            return;
          }
          if (!arg) {
            await this.sendDirectMessage(chatId, 'Usage: `/skills remove <category/slug>`');
            return;
          }
          if (!isValidSkillId(arg)) {
            await this.sendDirectMessage(chatId, 'Invalid skill id. Expected `<category>/<slug>`.');
            return;
          }
          const removed = store.remove(arg);
          if (!removed) {
            await this.sendDirectMessage(chatId, `Skill \`${arg}\` is not installed.`);
            return;
          }
          await this.sendDirectMessage(chatId, `🗑 Removed \`${arg}\`.`);
          return;
        }

        default: {
          await this.sendDirectMessage(
            chatId,
            `Unknown subcommand \`${sub}\`. Try \`/skills help\`.`,
          );
        }
      }
    } catch (err: any) {
      const msg = err?.message || 'Skill registry request failed';
      logger.warn({ err: msg, sub, arg }, 'Telegram /skills command failed');
      await this.sendDirectMessage(chatId, `⚠️ ${msg}`);
    }
  }

  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;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;');
  }

  private splitMessage(text: string, maxLen: number): string[] {
    if (text.length <= maxLen) return [text];
    const chunks: string[] = [];
    let remaining = text;
    while (remaining.length > 0) {
      let splitAt = maxLen;
      if (remaining.length > maxLen) {
        const lastNewline = remaining.lastIndexOf('\n', maxLen);
        if (lastNewline > maxLen * 0.5) {
          splitAt = lastNewline + 1;
        }
      }
      chunks.push(remaining.slice(0, splitAt));
      remaining = remaining.slice(splitAt);
    }
    return chunks;
  }

  private stripHtml(html: string): string {
    return html
      .replace(/<\/?(b|i|s|u|code|pre|a|blockquote|strong|em)[^>]*>/gi, '')
      .replace(/<pre><code[^>]*>/gi, '')
      .replace(/<\/code><\/pre>/gi, '')
      .replace(/<[^>]+>/g, '')
      .replace(/&lt;/g, '<')
      .replace(/&gt;/g, '>')
      .replace(/&amp;/g, '&');
  }

  /** Find the task-active key that matches a numeric chatId */
  private findActiveTaskKey(chatId: number): string | undefined {
    for (const [key, active] of this.taskActive) {
      if (!active) continue;
      // Keys can be 'notification', 'telegram:12345', or just '12345'
      if (key === 'notification') return key;
      const numericPart = key.startsWith('telegram:') ? key.split(':')[1] : key;
      if (numericPart === String(chatId)) return key;
    }
    return undefined;
  }

  /** Refresh the status card with current step history + notices */
  private async refreshStatusCard(targetId?: string): Promise<void> {
    const key = targetId || 'notification';
    const step = this.stepCounters.get(key) || 0;
    const history = this.stepHistory.get(key) || [];
    const notices = this.statusNotices.get(key) || [];
    // Heartbeat lines arrive every 20-60s for the whole task — keep only the tail
    // so the stored list (and the card) stays short.
    if (notices.length > TelegramChannel.MAX_STORED_STATUS_NOTICES) {
      notices.splice(0, notices.length - TelegramChannel.MAX_STORED_STATUS_NOTICES);
    }

    const recentHistory = history.slice(-5);
    const recentNotices = notices.slice(-TelegramChannel.MAX_STATUS_NOTICES);

    const lines = [
      `⚙️ **Mercury working** (step ${step})`,
      '',
      ...recentHistory.map(h => `✅ ${h}`),
    ];

    if (recentNotices.length > 0) {
      lines.push('');
      lines.push(...recentNotices.map(n => `💬 ${n}`));
    }

    await this.updateStatusMessage(lines.join('\n'), targetId);
  }

  private async updateStatusMessage(text: string, targetId?: string): Promise<void> {
    const key = targetId || 'notification';
    const previous = this.statusUpdateQueues.get(key) || Promise.resolve();
    const next = previous
      .catch(() => {})
      .then(() => this.updateStatusMessageNow(text, targetId));
    this.statusUpdateQueues.set(key, next);
    try {
      await next;
    } finally {
      if (this.statusUpdateQueues.get(key) === next) {
        this.statusUpdateQueues.delete(key);
      }
    }
  }

  private async updateStatusMessageNow(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 (err: any) {
          const description = err?.description || err?.message || '';
          if (String(description).includes('message is not modified')) {
            return;
          }
          await this.unpinStatusMessage(targetId);
          await this.bot.api.deleteMessage(chatId, existingMsgId).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 pendingUpdate = this.statusUpdateQueues.get(key);
    if (pendingUpdate) {
      await pendingUpdate.catch(() => {});
    }
    const msgId = this.statusMessageIds.get(key);
    if (msgId && this.bot) {
      // Unpin before deleting if this was pinned
      await this.unpinStatusMessage(targetId);
      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);
    }
  }

  /** Pin the current status message to the top of the chat (silently) */
  private async pinStatusMessage(targetId?: string): Promise<void> {
    if (!this.bot) return;
    const key = targetId || 'notification';
    const msgId = this.statusMessageIds.get(key);
    if (!msgId) return;

    const chatIds = this.resolveTargetChatIds(targetId);
    for (const chatId of chatIds) {
      // Failsafe: unpin any existing pinned message first
      const existingPin = this.pinnedMessageIds.get(key);
      if (existingPin && existingPin !== msgId) {
        await this.bot.api.unpinChatMessage(chatId, existingPin).catch(() => {});
        this.pinnedMessageIds.delete(key);
      }

      // Don't re-pin the same message
      if (existingPin === msgId) return;

      try {
        await this.bot.api.pinChatMessage(chatId, msgId, { disable_notification: true });
        this.pinnedMessageIds.set(key, msgId);
        logger.info({ chatId, msgId }, 'Pinned status message');
      } catch (err: any) {
        logger.warn({ err: err.message, chatId }, 'Failed to pin status message');
      }
    }
  }

  /** Unpin the current status message */
  private async unpinStatusMessage(targetId?: string): Promise<void> {
    if (!this.bot) return;
    const key = targetId || 'notification';
    const msgId = this.pinnedMessageIds.get(key);
    if (!msgId) return;

    const chatIds = this.resolveTargetChatIds(targetId);
    for (const chatId of chatIds) {
      await this.bot.api.unpinChatMessage(chatId, msgId).catch(() => {});
    }
    this.pinnedMessageIds.delete(key);
  }

  /** Track a message ID as ephemeral (will be deleted on task completion) */
  private trackEphemeral(targetId: string | undefined, messageId: number): void {
    const key = targetId || 'notification';
    const ids = this.ephemeralMessageIds.get(key) || [];
    ids.push(messageId);
    this.ephemeralMessageIds.set(key, ids);
  }

  /** Delete a specific ephemeral message immediately (e.g., after permission response) */
  private async deleteEphemeralMessage(targetId: string | undefined, messageId: number): Promise<void> {
    if (!this.bot) return;
    const chatIds = this.resolveTargetChatIds(targetId);
    for (const chatId of chatIds) {
      await this.bot.api.deleteMessage(chatId, messageId).catch(() => {});
    }
    // Remove from tracking
    const key = targetId || 'notification';
    const ids = this.ephemeralMessageIds.get(key);
    if (ids) {
      const idx = ids.indexOf(messageId);
      if (idx !== -1) ids.splice(idx, 1);
    }
  }

  /** Clean up all ephemeral messages for a chat (called on task completion) */
  async cleanupEphemeralMessages(targetId?: string): Promise<void> {
    if (!this.bot) return;
    const key = targetId || 'notification';
    const ids = this.ephemeralMessageIds.get(key) || [];
    const chatIds = this.resolveTargetChatIds(targetId);
    for (const chatId of chatIds) {
      for (const msgId of ids) {
        await this.bot.api.deleteMessage(chatId, msgId).catch(() => {});
      }
    }
    this.ephemeralMessageIds.delete(key);
  }

  resetStepCounter(targetId?: string): void {
    const key = targetId || 'notification';
    this.stepCounters.delete(key);
    this.stepHistory.delete(key);
    this.statusText.delete(key);
    this.statusNotices.delete(key);
    this.endTask(targetId);
    this.deleteStatusMessage(targetId);
  }

  async sendCompletion(elapsedMs: number, stepCount: number, targetId?: string, meta?: { provider: string; model: string; inputTokens: number; outputTokens: number; totalTokens: number; budgetUsed: number; budgetTotal: number; budgetPercentage: number }): Promise<void> {
    const key = targetId || 'notification';
    logger.info({ elapsedMs, stepCount, provider: meta?.provider, model: meta?.model }, 'Telegram task complete');

    // Clean up: unpin + delete the status card, clean up ephemeral messages
    await this.deleteStatusMessage(targetId);
    await this.cleanupEphemeralMessages(targetId);

    // End the task so deferred response flush uses normal send()
    this.endTask(targetId);

    const chatIds = this.resolveTargetChatIds(targetId);

    // Flush deferred AI response first (the actual answer the user wants to see)
    const deferred = this.deferredResponses.get(key);
    if (deferred && deferred.trim()) {
      await this.send(deferred, targetId);
    }

    this.stepCounters.delete(key);
    this.stepHistory.delete(key);
    this.statusText.delete(key);
    this.statusMessageIds.delete(key);
    this.statusNotices.delete(key);
  }

  private isImageFile(ext: string): boolean {
    return ['.jpg', '.jpeg', '.png', '.webp'].includes(ext);
  }

  private isAudioFile(ext: string): boolean {
    return ['.mp3', '.ogg', '.wav', '.flac', '.m4a'].includes(ext);
  }

  private isVideoFile(ext: string): boolean {
    return ['.mp4', '.mov', '.avi', '.mkv', '.webm'].includes(ext);
  }

  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((e: any) => logger.warn({ e }, "telegram send failed"));
    }
  }

  /**
   * Send a feedback request to the admin via Telegram with inline keyboard options.
   * Returns the user's response as a string.
   */
  async sendFeedbackRequest(feedbackId: string, boardName: string, cardTask: string, question: string, options?: string[]): Promise<string | null> {
    if (!this.bot) return null;

    // Find admin chat
    const admin = this.getAdminUser();
    if (!admin) return null;

    const header = `🔔 <b>Feedback Required</b>\n\n<b>Board:</b> ${this.escapeHtml(boardName)}\n<b>Card:</b> ${this.escapeHtml(cardTask)}\n\n${this.escapeHtml(question)}`;

    const keyboard = new InlineKeyboard();
    if (options && options.length > 0) {
      for (const opt of options) {
        keyboard.text(opt, `feedback:${feedbackId}:${opt}`).row();
      }
    }
    keyboard.text('💬 Type custom response', `feedback:${feedbackId}:__custom__`);

    try {
      await this.bot.api.sendMessage(admin.chatId, header, {
        parse_mode: 'HTML',
        reply_markup: keyboard,
      });
    } catch {
      try {
        await this.bot.api.sendMessage(admin.chatId, `Feedback Required\n\nBoard: ${boardName}\nCard: ${cardTask}\n\n${question}`, {
          reply_markup: keyboard,
        });
      } catch { return null; }
    }
    return null; // Response comes via callback_query handler
  }

  private getAdminUser(): { chatId: number } | null {
    // Access the first admin user from approved list
    const users = (this as any).approvedUsers as Map<number, any> | undefined;
    if (!users) return null;
    for (const [chatId, user] of users) {
      if (user.role === 'admin') return { chatId };
    }
    // Fallback: first user
    for (const [chatId] of users) {
      return { chatId };
    }
    return null;
  }

  private cleanupDedup(): void {
    const now = Date.now();
    for (const [key, ts] of this.processedMessages) {
      if (now - ts > TelegramChannel.DEDUP_TTL) {
        this.processedMessages.delete(key);
      }
    }
  }
}