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.

v0.2.2 — Telegram inline keyboard for permission approvals

Salman Qureshi8b1192848f5b
diff --git a/package.json b/package.json
index b3b610d4..9d9dcd80 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "@cosmicstack/mercury-agent",
- "version": "0.2.1",
+ "version": "0.2.2",
"description": "Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI or Telegram.",
"type": "module",
"main": "dist/index.js",
diff --git a/src/capabilities/permissions.ts b/src/capabilities/permissions.ts
index 6e718cab..ed5d4538 100644
--- a/src/capabilities/permissions.ts
+++ b/src/capabilities/permissions.ts
@@ -130,12 +130,21 @@ export class PermissionManager {
private autoApproveAll = false;
private elevatedCommands: Set<string> = new Set();
private pendingApprovals: Set<string> = new Set();
+ private currentChannelType: string = 'cli';
constructor() {
this.cwd = process.cwd();
this.manifest = this.load();
}
+ setCurrentChannelType(type: string): void {
+ this.currentChannelType = type;
+ }
+
+ getCurrentChannelType(): string {
+ return this.currentChannelType;
+ }
+
onAsk(handler: (prompt: string) => Promise<string>): void {
this.askHandler = handler;
}
@@ -289,10 +298,33 @@ export class PermissionManager {
for (const pattern of shell.needsApproval) {
if (this.matchPattern(trimmed, pattern)) {
+ if (this.currentChannelType === 'telegram' && this.askHandler) {
+ const result = await this.askHandler(`Run command: ${trimmed}`);
+ if (result === 'yes') {
+ return { allowed: true, needsApproval: false };
+ }
+ if (result === 'always') {
+ this.addApprovedCommand(baseCmd);
+ return { allowed: true, needsApproval: false };
+ }
+ return { allowed: false, reason: `User denied: ${trimmed}`, needsApproval: false };
+ }
return { allowed: false, reason: `Command requires approval: matches "${pattern}"`, needsApproval: true };
}
}
+ if (this.currentChannelType === 'telegram' && this.askHandler) {
+ const result = await this.askHandler(`Run command: ${trimmed}`);
+ if (result === 'yes') {
+ return { allowed: true, needsApproval: false };
+ }
+ if (result === 'always') {
+ this.addApprovedCommand(baseCmd);
+ return { allowed: true, needsApproval: false };
+ }
+ return { allowed: false, reason: `User denied: ${trimmed}`, needsApproval: false };
+ }
+
return { allowed: false, reason: 'Command not in auto-approve list — requires approval', needsApproval: true };
}
diff --git a/src/channels/telegram.ts b/src/channels/telegram.ts
index 0aa1bb2c..85da4d5e 100644
--- a/src/channels/telegram.ts
+++ b/src/channels/telegram.ts
@@ -1,6 +1,6 @@
import fs from 'node:fs';
import path from 'node:path';
-import { Bot, InputFile } from 'grammy';
+import { Bot, InputFile, InlineKeyboard } from 'grammy';
import { autoRetry } from '@grammyjs/auto-retry';
import type { ChannelMessage } from '../types/channel.js';
import { BaseChannel } from './base.js';
@@ -10,12 +10,15 @@ import { mdToTelegram } from '../utils/markdown.js';
const MAX_MESSAGE_LENGTH = 4096;
+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 typingInterval: NodeJS.Timeout | null = null;
private chatCommandContext?: import('../capabilities/registry.js').ChatCommandContext;
+ private pendingApprovals: Map<string, ApprovalResolver> = new Map();
constructor(private config: MercuryConfig) {
super();
@@ -55,6 +58,21 @@ export class TelegramChannel extends BaseChannel {
this.emit(msg);
});
+ bot.on('callback_query:data', async (ctx) => {
+ const data = ctx.callbackQuery.data;
+ const resolver = this.pendingApprovals.get(data);
+ if (!resolver) {
+ await ctx.answerCallbackQuery({ text: 'Expired' });
+ return;
+ }
+
+ this.pendingApprovals.delete(data);
+
+ const action = data.split(':')[1] as 'yes' | 'always' | 'no';
+ resolver(action);
+ await ctx.answerCallbackQuery({ text: action === 'no' ? 'Denied' : 'Approved' });
+ });
+
bot.catch((err) => {
logger.error({ err: err.message }, 'Telegram bot error');
});
@@ -262,6 +280,43 @@ export class TelegramChannel extends BaseChannel {
}
}
+ async askPermission(prompt: string, targetId?: string): Promise<string> {
+ const chatId = this.parseChatId(targetId);
+ 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`);
+
+ const html = mdToTelegram(prompt);
+
+ 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,
+ });
+ }
+
+ return new Promise((resolve) => {
+ this.pendingApprovals.set(`${id}:yes`, () => resolve('yes'));
+ this.pendingApprovals.set(`${id}:always`, () => resolve('always'));
+ this.pendingApprovals.set(`${id}:no`, () => resolve('no'));
+
+ setTimeout(() => {
+ this.pendingApprovals.delete(`${id}:yes`);
+ this.pendingApprovals.delete(`${id}:always`);
+ this.pendingApprovals.delete(`${id}:no`);
+ resolve('no');
+ }, 120_000);
+ });
+ }
+
private escapeHtml(text: string): string {
return text
.replace(/&/g, '&amp;')
diff --git a/src/core/agent.ts b/src/core/agent.ts
index 52925f73..fda03944 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -215,6 +215,7 @@ export class Agent {
}
this.capabilities.setChannelContext(msg.channelId, msg.channelType);
+ this.capabilities.permissions.setCurrentChannelType(msg.channelType);
const fallbackIterator = this.providers.getFallbackIterator();
let result: any = null;
diff --git a/src/index.ts b/src/index.ts
index e7858b08..91f7df5a 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -313,12 +313,18 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
await agent.wake();
const cliChannel = channels.get('cli') as CLIChannel | undefined;
+ const tgChannel = channels.get('telegram') as TelegramChannel | undefined;
- if (cliChannel) {
- capabilities.permissions.onAsk(async (prompt: string) => {
+ capabilities.permissions.onAsk(async (prompt: string) => {
+ const channelType = capabilities.permissions.getCurrentChannelType();
+ if (channelType === 'telegram' && tgChannel) {
+ return tgChannel.askPermission(prompt);
+ }
+ if (cliChannel) {
return cliChannel.askPermission(prompt);
- });
- }
+ }
+ return 'no';
+ });
const activeCh = channels.getActiveChannels();
const toolNames = capabilities.getToolNames();