Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
permission mode: ask-me vs allow-all at session start, auto-continue loops in allow-all
Salman Qureshi75dc3776c168
diff --git a/src/capabilities/permissions.ts b/src/capabilities/permissions.tsindex d2ed2495..3a3f1966 100644--- a/src/capabilities/permissions.ts+++ b/src/capabilities/permissions.ts@@ -155,6 +155,10 @@ export class PermissionManager {this.autoApproveAll = value;}+ isAutoApproveAll(): boolean {+ return this.autoApproveAll;+ }+elevateForSkill(allowedTools: string[]): void {if (allowedTools.includes('run_command')) {this.elevatedCommands.add('run_command');diff --git a/src/channels/base.ts b/src/channels/base.tsindex 9b748b20..8f7a98c4 100644--- a/src/channels/base.ts+++ b/src/channels/base.ts@@ -1,5 +1,7 @@import type { ChannelType, ChannelMessage } from '../types/channel.js';+export type PermissionMode = 'allow-all' | 'ask-me';+export interface Channel {readonly type: ChannelType;start(): Promise<void>;@@ -9,6 +11,7 @@ export interface Channel {stream(content: AsyncIterable<string>, targetId?: string): Promise<string>;typing(targetId?: string): Promise<void>;askToContinue(question: string, targetId?: string): Promise<boolean>;+ askPermissionMode?(): Promise<PermissionMode>;isReady(): boolean;onMessage(handler: (msg: ChannelMessage) => void): void;}diff --git a/src/channels/cli.ts b/src/channels/cli.tsindex 9052b68a..c8616bc4 100644--- a/src/channels/cli.ts+++ b/src/channels/cli.ts@@ -3,7 +3,7 @@ import fs from 'node:fs';import path from 'node:path';import chalk from 'chalk';import type { ChannelMessage } from '../types/channel.js';-import { BaseChannel } from './base.js';+import { BaseChannel, type PermissionMode } from './base.js';import { logger } from '../utils/logger.js';import { renderMarkdown } from '../utils/markdown.js';import { formatToolStep, formatToolResult } from '../utils/tool-label.js';@@ -308,6 +308,48 @@ export class CLIChannel extends BaseChannel {});}+ async askPermissionMode(): Promise<PermissionMode> {+ if (!process.stdout.isTTY) return 'ask-me';++ this.suspendPrompt();++ console.log('');+ console.log(chalk.bold(' Permission Mode'));+ console.log(chalk.dim(' Choose how Mercury handles risky actions this session.'));+ console.log('');++ const options: ArrowSelectOption[] = [+ { value: 'ask-me', label: 'Ask Me — confirm before file writes, shell commands, and scope changes' },+ { value: 'allow-all', label: 'Allow All — auto-approve everything (scopes, commands, loop continuation)' },+ ];++ try {+ const selected = await selectWithArrowKeys('Select permission mode:', options, {+ helperText: '↑↓ to move, Enter to select',+ });++ if (selected === 'allow-all') {+ console.log('');+ console.log(chalk.yellow(' ⚠ Allow All active for this session:'));+ console.log(chalk.dim(' • All directory scopes auto-approved'));+ console.log(chalk.dim(' • All shell commands auto-approved (except blocked)'));+ console.log(chalk.dim(' • Loop detection will auto-continue'));+ console.log(chalk.dim(' • Resets on restart'));+ console.log('');+ } else {+ console.log('');+ console.log(chalk.dim(' Confirm-before-act mode active.'));+ console.log('');+ }++ return selected as PermissionMode;+ } catch {+ return 'ask-me';+ } finally {+ this.resumePrompt();+ }+ }+async askPermission(prompt: string): Promise<string> {return new Promise((resolve) => {console.log('');diff --git a/src/channels/telegram.ts b/src/channels/telegram.tsindex 188147b2..1ffd13bd 100644--- a/src/channels/telegram.ts+++ b/src/channels/telegram.ts@@ -3,7 +3,7 @@ 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 } from './base.js';+import { BaseChannel, type PermissionMode } from './base.js';import type { MercuryConfig, TelegramAccessUser, TelegramPendingRequest } from '../utils/config.js';import {addTelegramPendingRequest,@@ -25,7 +25,7 @@ import { mdToTelegram } from '../utils/markdown.js';const MAX_MESSAGE_LENGTH = 4096;const ACCESS_ACTION_PREFIX = 'tg_access';-type ApprovalResolver = (response: 'yes' | 'always' | 'no') => void;+type ApprovalResolver = () => void;export class TelegramChannel extends BaseChannel {readonly type = 'telegram' as const;@@ -34,6 +34,8 @@ 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 onPermissionMode?: (mode: PermissionMode, chatId: number) => void;constructor(private config: MercuryConfig) {super();@@ -43,6 +45,10 @@ export class TelegramChannel extends BaseChannel {this.chatCommandContext = ctx;}+ setOnPermissionMode(handler: (mode: PermissionMode, chatId: number) => void): void {+ this.onPermissionMode = handler;+ }+async start(): Promise<void> {const token = this.config.channels.telegram.botToken;if (!token) {@@ -87,6 +93,12 @@ 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 (command === '/unpair') {if (!this.isAdminUser(userId)) {await this.sendDirectMessage(chatId, 'Only Telegram admins can reset Telegram access.');@@ -128,9 +140,8 @@ export class TelegramChannel extends BaseChannel {}this.pendingApprovals.delete(data);-- const action = data.split(':')[1] as 'yes' | 'always' | 'no';- resolver(action);+ resolver();+ const action = data.split(':')[1];await ctx.answerCallbackQuery({ text: action === 'no' ? 'Denied' : 'Approved' });});@@ -441,6 +452,41 @@ export class TelegramChannel extends BaseChannel {});}+ 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)`;++ 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}:ask-me`, () => resolve('ask-me'));+ this.pendingApprovals.set(`${id}:allow-all`, () => resolve('allow-all'));++ setTimeout(() => {+ this.pendingApprovals.delete(`${id}:ask-me`);+ this.pendingApprovals.delete(`${id}:allow-all`);+ resolve('ask-me');+ }, 120_000);+ });+ }+private async handleAccessRequest(userId: number,chatId: number,diff --git a/src/core/agent.ts b/src/core/agent.tsindex 4f774fa7..c3947bd0 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -395,16 +395,21 @@ export class Agent {}const softLoop = loopDetector.detectSameTool();if (softLoop && !loopWarningSent && channel && msg.channelType !== 'internal') {- loopWarningSent = true;- const shouldContinue = await channel.askToContinue(- `${softLoop.tool} has been called ${softLoop.count}x in a row. This might be a loop.`,- msg.channelId,- ).catch(() => false);- if (shouldContinue) {+ if (this.capabilities.permissions.isAutoApproveAll()) {loopDetector.reset();loopWarningSent = false;} else {- loopAbortController.abort();+ loopWarningSent = true;+ const shouldContinue = await channel.askToContinue(+ `${softLoop.tool} has been called ${softLoop.count}x in a row. This might be a loop.`,+ msg.channelId,+ ).catch(() => false);+ if (shouldContinue) {+ loopDetector.reset();+ loopWarningSent = false;+ } else {+ loopAbortController.abort();+ }}}if (channel && msg.channelType !== 'internal') {@@ -493,16 +498,21 @@ export class Agent {}const softLoop = loopDetector.detectSameTool();if (softLoop && !loopWarningSent && channel && msg.channelType !== 'internal') {- loopWarningSent = true;- const shouldContinue = await channel.askToContinue(- `${softLoop.tool} has been called ${softLoop.count}x in a row. This might be a loop.`,- msg.channelId,- ).catch(() => false);- if (shouldContinue) {+ if (this.capabilities.permissions.isAutoApproveAll()) {loopDetector.reset();loopWarningSent = false;} else {- loopAbortController.abort();+ loopWarningSent = true;+ const shouldContinue = await channel.askToContinue(+ `${softLoop.tool} has been called ${softLoop.count}x in a row. This might be a loop.`,+ msg.channelId,+ ).catch(() => false);+ if (shouldContinue) {+ loopDetector.reset();+ loopWarningSent = false;+ } else {+ loopAbortController.abort();+ }}}if (channel && msg.channelType !== 'internal') {diff --git a/src/index.ts b/src/index.tsindex 91bca0fa..8c20251b 100644--- a/src/index.ts+++ b/src/index.ts@@ -934,6 +934,16 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {return 'no';});+ if (tgChannel) {+ tgChannel.setOnPermissionMode((mode, chatId) => {+ if (mode === 'allow-all') {+ capabilities.permissions.setAutoApproveAll(true);+ capabilities.permissions.addTempScope('/', true, true);+ logger.info({ chatId }, 'Telegram: Allow All mode set for session');+ }+ });+ }+const activeCh = channels.getActiveChannels();const toolNames = capabilities.getToolNames();@@ -942,6 +952,13 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {console.log(chalk.dim(` Creator: ${config.identity.creator}`));}hr();++ const mode = cliChannel && await cliChannel.askPermissionMode?.();+ if (mode === 'allow-all') {+ capabilities.permissions.setAutoApproveAll(true);+ capabilities.permissions.addTempScope('/', true, true);+ }+console.log('');console.log(chalk.green(` ${name} is live. Type a message and press Enter.`));console.log(chalk.dim(' Ctrl+C to exit · /help for commands'));