Agent Zero AI framework
Extend slash commands coverage and menus in Telegram
Alessandro17033d277e4a
diff --git a/plugins/_commands/AGENTS.md b/plugins/_commands/AGENTS.mdindex 7039e101b..20ff44f66 100644--- a/plugins/_commands/AGENTS.md+++ b/plugins/_commands/AGENTS.md@@ -35,6 +35,7 @@- Selected reference icons may use the composer highlight color while their labels keep the normal text color; serialized prompt text remains unchanged.- File and folder references stay inside the active chat workdir and list one directory at a time through the existing file-browser and chat-path APIs. Profile and effective MCP server references reuse their scoped catalogs; skill references use only entries visible in the active chat scope.- WebUI sends resolve through the picker effect path, while backend-originated messages resolve before reaching the agent.+- Telegram's plugin resolves raw messages through this catalog before adding its message envelope, adapting effects to Telegram and retaining integration-specific controls. Command discovery and script/template execution remain owned here.- `/stop` uses the same shared cancellation operation as the composer Stop button, including progress cleanup and terminal logging.- `/profile` opens Manage agents without arguments, keeps existing profileselection, and creates through Agent Editor when given a name and instructions.diff --git a/plugins/_telegram_integration/AGENTS.md b/plugins/_telegram_integration/AGENTS.mdindex caa06d948..487fdf485 100644--- a/plugins/_telegram_integration/AGENTS.md+++ b/plugins/_telegram_integration/AGENTS.md@@ -8,14 +8,23 @@- `helpers/bot_manager.py` owns bot lifecycle.- `helpers/handler.py` and `helpers/telegram_client.py` own message routing, replies, and Telegram API interaction.+- `helpers/slash_commands.py` adapts the shared Commands resolver and effects to Telegram replies, menus, session bindings, exports, and compaction confirmation.+- `helpers/settings_ui.py` owns Telegram plugin toggles and tool-permission menus, delegating writes to the existing plugin and Agent Editor owners.+- `hooks.py` normalizes saved/read bot configurations, supplies stable names for unnamed bots, and rejects duplicate names on save.- `helpers/dependencies.py` and `requirements.txt` own framework-runtime dependency bootstrap.- `api/`, `prompts/`, `extensions/`, `default_config.yaml`, `plugin.yaml`, `README.md`, and `webui/` own tests/webhook endpoints, prompt fragments, hooks, settings, metadata, docs, and UI.-- `webui/config.html` is the sole plugin UI, including bot setup and connection checks.+- `webui/config.html` is the sole plugin WebUI, including bot setup and connection checks.## Local Contracts- Treat bot tokens, chat IDs, attachments, and user data as sensitive.- Keep allowed-user, group-mode, project, model, and `/send` controls enforced.+- Resolve raw commands before adding the Telegram message envelope; its closing marker prevents queued/rendered text from being interpreted as a second postfix command. Custom/project definitions override bundled commands; keep Telegram's existing integration aliases and pickers for unoverridden commands.+- `/commands` discovers the current chat's effective commands on each use. The native Telegram menu registers global commands at startup, maps hyphens to underscores, and obeys Telegram's name/description/count limits.+- Render text/script results and supported effects in Telegram. Browser-only settings return guidance instead of pretending to open a modal; host computer permissions remain controlled by Launcher/CLI.+- Permission callbacks bind canonical tool IDs to the current context/project/profile, revalidate the live catalog, and refuse changes during an active run. Required tools stay outside the menu. Plugin toggles are instance-wide, protect always-enabled plugins, and keep Telegram/Commands enabled so the connection remains controllable.+- `/new` creates and binds a fresh context without resetting the previous chat. `/clear` retains Telegram's existing reset behavior. Compaction confirms the current idle context and uses the existing backup-producing compactor.+- Restart bots when their token, delivery mode, group mode, webhook URL, or webhook secret changes. Polling may start on the next job-loop tick after saving settings.- Webhook dispatch requires an active webhook and a matching nonempty secret header. Setup requires a random 32–256 character secret using letters, digits, `_` or `-`; polling and webhook removal revoke HTTP delivery.- Install Telegram dependencies into the framework runtime only when required.- Keep project and agent-profile configuration scopes available through the shared plugin settings modal.@@ -33,6 +42,7 @@## Verification- Smoke-test connection checks, polling or webhook delivery, per-user context reuse, attachments, and replies when practical.+- Run `PYTHONPATH=. conda run -n a0 python -m pytest -q tests/test_telegram_commands.py tests/test_telegram_webhook_security.py` for command routing, menu bounds, configuration normalization, and bot lifecycle regressions.## Child DOX Indexdiff --git a/plugins/_telegram_integration/README.md b/plugins/_telegram_integration/README.mdindex 327b65d08..a0911aaad 100644--- a/plugins/_telegram_integration/README.md+++ b/plugins/_telegram_integration/README.md@@ -15,10 +15,16 @@ This plugin connects one or more Telegram bots to Agent Zero. Each bot runs inde- Managed by a `job_loop` extension that starts, restarts, or stops bots whenever plugin settings change.- Supports both long-polling and webhook delivery modes. Webhook mode requires a random secret of 32–256 letters, digits, underscores or hyphens; generate one with `python -c 'import secrets; print(secrets.token_urlsafe(32))'`. Existing webhook configurations without a valid secret must be updated before starting the bot.- The webhook endpoint rejects polling bots and requires a matching `X-Telegram-Bot-Api-Secret-Token` header before dispatch.+ - Bot names are generated automatically if left empty. Each bot needs a unique name; saving a new token or webhook connection restarts that bot on the next maintenance tick (up to about a minute).- **Per-user chat sessions**- Each Telegram user gets a dedicated `AgentContext`, persisted across restarts via a JSON state file.- `/start` creates a context; `/new` starts fresh; `/clear` resets the current context.- `/commands` shows the shared integration command menu (`/help` is an alias).+ - `/commands` also provides a paginated menu of Agent Zero's built-in, enabled-plugin, global, and active-project commands. Custom commands use the same templates, scripts, and scope precedence as the WebUI, including prefix and postfix syntax.+ - `/stop`, `/goal`, and `/rename` execute their existing Agent Zero commands. `/compact` offers confirmation before summarizing, preserving the existing conversation backup. `/copy` sends the transcript as a text file; `/attach` explains Telegram's native attachment control.+ - `/models` and `/presets` open the model preset picker; `/chats` opens the session picker, and `/chat <id>` switches sessions. `/browser` offers runtime buttons.+ - `/plugins` provides paginated instance-wide plugin toggles. `/permissions` edits the current profile's tool permissions, including Allow/Block/Default per tool, separate Tools/MCP defaults, and inherited policy. Always-required tools and the Telegram connection remain protected. Computer Use permissions stay with A0 Launcher/CLI.+ - Telegram's native command menu includes global commands at bot startup. Hyphenated commands also accept an underscore spelling, such as `/computer_use`; use `/commands` for freshly added or project-specific commands.- `/status` shows project, model, agent profile, and queue state.- `/project <name>` switches the active project for the current chat.- `/model <preset>` switches the active model preset for the current chat (`/config` remains an alias).@@ -87,8 +93,8 @@ This plugin connects one or more Telegram bots to Agent Zero. Each bot runs inde## Configuration Scope- **Settings section**: `external`-- **Per-project config**: `false`-- **Per-agent config**: `false`+- **Per-project config**: `true`+- **Per-agent config**: `true`## Plugin Metadatadiff --git a/plugins/_telegram_integration/extensions/python/job_loop/_10_telegram_bot.py b/plugins/_telegram_integration/extensions/python/job_loop/_10_telegram_bot.pyindex dff9222ef..d8fee801d 100644--- a/plugins/_telegram_integration/extensions/python/job_loop/_10_telegram_bot.py+++ b/plugins/_telegram_integration/extensions/python/job_loop/_10_telegram_bot.py@@ -63,7 +63,14 @@ class TelegramBotManager(Extension):current_mode = bot_cfg.get("mode", "polling")running_mode = "webhook" if inst.webhook_active else "polling"current_group_mode = bot_cfg.get("group_mode", "mention")- if current_mode == running_mode and current_group_mode == inst.group_mode:+ same_connection = (+ bot_cfg["token"] == inst.bot.token+ and (current_mode != "webhook" or (+ bot_cfg.get("webhook_url", "").rstrip("/") == inst.webhook_url+ and bot_cfg.get("webhook_secret", "") == inst.webhook_secret+ ))+ )+ if current_mode == running_mode and current_group_mode == inst.group_mode and same_connection:# Same mode and still alive → skipif (inst.task and not inst.task.done()) or inst.webhook_active:continuediff --git a/plugins/_telegram_integration/helpers/bot_manager.py b/plugins/_telegram_integration/helpers/bot_manager.pyindex 5b4a4c329..58486e224 100644--- a/plugins/_telegram_integration/helpers/bot_manager.py+++ b/plugins/_telegram_integration/helpers/bot_manager.py@@ -24,6 +24,7 @@ class BotInstance:task: asyncio.Task | None = None # polling taskwebhook_active: bool = False # True when webhook mode is registeredwebhook_secret: str = "" # secret for webhook verification+ webhook_url: str = ""group_mode: str = "mention" # current group_mode settingbot_info: object | None = None # cached result of bot.get_me()@@ -56,11 +57,13 @@ def create_bot(router = Router()# Register command handlers- router.message.register(on_command_start, CommandStart())+ command_filters = [F.chat.type == ChatType.PRIVATE] if group_mode == "off" else []+ router.message.register(on_command_start, CommandStart(), *command_filters)if on_command_control:router.message.register(on_command_control,Command(commands=integration_commands.command_names(integration="telegram")),+ *command_filters,)if on_callback_query:@@ -94,10 +97,12 @@ def create_bot(async def register_bot_commands(instance: BotInstance) -> None:- """Register Telegram's native / command menu from the shared integration registry."""+ """Register native integration and globally available Agent Zero commands."""+ from plugins._telegram_integration.helpers.slash_commands import menu_commands+commands = [BotCommand(command=name, description=description)- for name, description in integration_commands.telegram_menu_commands()+ for name, description in menu_commands()]if not commands:return@@ -204,12 +209,14 @@ async def setup_webhook(instance: BotInstance, webhook_url: str, secret: str = "instance.webhook_active = Trueinstance.webhook_secret = secret+ instance.webhook_url = webhook_url.rstrip("/")PrintStyle.info(f"Telegram ({instance.name}): webhook active via {webhook_url.rstrip('/')}")async def remove_webhook(instance: BotInstance):instance.webhook_active = Falseinstance.webhook_secret = ""+ instance.webhook_url = ""try:await instance.bot.delete_webhook()except Exception as e:diff --git a/plugins/_telegram_integration/helpers/handler.py b/plugins/_telegram_integration/helpers/handler.pyindex 5adad0e12..fc3526e05 100644--- a/plugins/_telegram_integration/helpers/handler.py+++ b/plugins/_telegram_integration/helpers/handler.py@@ -13,7 +13,6 @@ from aiogram.types import Message as TgMessage, CallbackQueryfrom agent import AgentContext, UserMessagefrom helpers import plugins, files, projectsfrom helpers import message_queue as mq-from helpers import integration_commandsfrom helpers.notification import NotificationManager, NotificationType, NotificationPriorityfrom helpers.persist_chat import save_tmp_chatfrom helpers.print_style import PrintStyle@@ -22,6 +21,7 @@ from initialize import initialize_agentfrom plugins._telegram_integration.helpers import telegram_client as tcfrom plugins._telegram_integration.helpers import command_ui+from plugins._telegram_integration.helpers import slash_commandsfrom plugins._telegram_integration.helpers.bot_manager import get_botfrom plugins._telegram_integration.helpers.constants import (PLUGIN_NAME,@@ -177,34 +177,13 @@ async def handle_message(message: TgMessage, bot_name: str, bot_cfg: dict):context.data[CTX_TG_CHAT_TYPE] = str(message.chat.type or "")context.data[CTX_TG_REPLY_TO] = message.message_id- if await command_ui.handle_command(- context,- instance.bot.token,- message.chat.id,- message.message_id,- text,- ):+ text = _normalize_bot_command(text, instance)+ if text is None:return-- command_reply = integration_commands.try_handle_command(context, text, integration="telegram")- if command_reply is not None:- await _send_with_temp_bot(- instance.bot.token,- message.chat.id,- command_reply,- parse_mode=None,- reply_to_message_id=message.message_id,- )- return- if integration_commands.extract_command_line(text).startswith("/"):- command = integration_commands.extract_command_line(text).split(" ", 1)[0]- await _send_with_temp_bot(- instance.bot.token,- message.chat.id,- integration_commands.unknown_command_text(command, integration="telegram"),- parse_mode=None,- reply_to_message_id=message.message_id,- )+ text = await slash_commands.handle(+ context, instance.bot.token, message.chat.id, message.message_id, text,+ )+ if text is None:return# Use temp bot for downloads (cross-event-loop safe)@@ -286,8 +265,17 @@ async def handle_callback_query(query: CallbackQuery, bot_name: str, bot_cfg: dicontext.data[CTX_TG_REPLY_TO] = query.message.message_idinstance = get_bot(bot_name)+ handled = Falseif instance:try:+ handled, command_text = await slash_commands.handle_callback(+ context, instance.bot.token, query.message.chat.id,+ query.message.message_id, text,+ )+ if handled:+ if command_text is None:+ return+ text = command_textif await command_ui.handle_callback(context,instance.bot.token,@@ -298,22 +286,21 @@ async def handle_callback_query(query: CallbackQuery, bot_name: str, bot_cfg: direturnexcept Exception as e:PrintStyle.error(f"Telegram callback failed: {format_error(e)}")- if text.startswith("tg:"):+ if text.startswith(("tg:", "a0:")):+ await slash_commands.reply(instance.bot.token, query.message.chat.id,+ query.message.message_id, f"Command failed: {e}")return- if text.startswith("tg:"):+ if text.startswith(("tg:", "a0:")):return- command_reply = integration_commands.try_handle_command(context, text, integration="telegram")- if command_reply is not None:- if instance:- await _send_with_temp_bot(- instance.bot.token,- query.message.chat.id,- command_reply,- parse_mode=None,- reply_to_message_id=query.message.message_id,- )- return+ if instance and not handled:+ text = _normalize_bot_command(text, instance)+ if text is None:+ return+ text = await slash_commands.handle(context, instance.bot.token,+ query.message.chat.id, query.message.message_id, text)+ if text is None:+ returnagent = context.agent0user_msg = agent.read_prompt(@@ -323,6 +310,13 @@ async def handle_callback_query(query: CallbackQuery, bot_name: str, bot_cfg: di)msg_id = str(uuid.uuid4())+ if context.is_running():+ mq.add(context, user_msg, [])+ save_tmp_chat(context)+ if instance:+ await slash_commands.reply(instance.bot.token, query.message.chat.id,+ query.message.message_id, "Message queued. Use /send to flush it or /steer to intervene.")+ returnmq.log_user_message(context, user_msg, [], message_id=msg_id, source=" (telegram)")context.communicate(UserMessage(message=user_msg, id=msg_id))save_tmp_chat(context)@@ -387,6 +381,7 @@ async def _get_or_create_context_from_user(ctx = AgentContext.get(ctx_id)if ctx:ctx.data[CTX_TG_CHAT_TYPE] = chat_type or ctx.data.get(CTX_TG_CHAT_TYPE, "")+ ctx.data[CTX_TG_BOT_CFG] = bot_cfgreturn ctx# Context was garbage collected, remove stale mappingchats.pop(key, None)@@ -425,6 +420,18 @@ async def _get_or_create_context_from_user(# Message content extraction+def _normalize_bot_command(text: str, instance) -> str | None:+ """Remove this bot's command suffix; ignore commands addressed to other bots."""+ import re++ match = re.match(r"^(\s*/[^\s@]+)@([^\s]+)([\s\S]*)$", text)+ if not match:+ return text+ username = getattr(instance.bot_info, "username", "") or ""+ if match.group(2).casefold() != username.casefold():+ return None+ return match.group(1) + match.group(3)+def _extract_message_content(message: TgMessage) -> str:parts = []diff --git a/plugins/_telegram_integration/helpers/settings_ui.py b/plugins/_telegram_integration/helpers/settings_ui.pynew file mode 100644index 000000000..0e6a159df--- /dev/null+++ b/plugins/_telegram_integration/helpers/settings_ui.py@@ -0,0 +1,113 @@+"""Telegram controls backed by the existing plugin and Agent Editor owners."""+from hashlib import sha256++from helpers import plugins, projects, tool_policy+from plugins._agent_editor.helpers import editor+from plugins._telegram_integration.helpers import telegram_client as tc+++def _key(context, item):+ scope = f"{context.id}:{projects.get_context_project_name(context)}:{context.config.profile}:{item}"+ return sha256(scope.encode()).hexdigest()[:24]+++def _plugin_items():+ return [(name, plugins.get_plugin_meta(name)) for name in sorted(plugins.get_plugins_list())+ if plugins.get_plugin_meta(name)]+++async def show(context, token, chat_id, message_id, kind, page=0):+ if kind == "permissions" and context.config.profile == "default":+ raise ValueError("The Default utility profile has no editable permissions. Use /profile first.")+ items = _plugin_items() if kind == "plugins" else tool_policy.get_tool_catalog(context.agent0)+ page = min(max(0, page), max(0, (len(items) - 1) // 8))+ rows = []+ if kind == "plugins":+ title = "Installed plugins (instance-wide)"+ for name, meta in items[page * 8:page * 8 + 8]:+ enabled = plugins.get_toggle_state(name) == "enabled"+ locked = meta.always_enabled or name in {"_telegram_integration", "_commands"}+ action = "noop" if locked else ("off" if enabled else "on")+ rows.append([{"text": f"{'On' if enabled else 'Off'} — {meta.title}"[:64],+ "callback_data": f"a0:plugin:{action}:{_key(context, name)}"}])+ title += "\nTap to enable or disable. Required plugins and this Telegram connection stay enabled here."+ else:+ policy = tool_policy.get_policy(context.agent0)+ title = f"Tool permissions: {context.config.profile}\nScope: {projects.get_context_project_name(context) or 'Global'}"+ for item in items[page * 8:page * 8 + 8]:+ allowed = tool_policy.resolve_tool(context.agent0, item['name'], canonical_id=item['id'], _policy=policy).allowed+ rows.append([{"text": f"{'Allow' if allowed else 'Block'} — {item['label']}"[:64],+ "callback_data": f"a0:tool:{_key(context, item['id'])}"}])+ for field, label in (("default", "Tools default"), ("mcp_default", "MCP default")):+ value = policy[field] if policy['mode'] == 'custom' else 'allow'+ action = 'block' if value == 'allow' else 'allow'+ rows.append([{"text": f"{label}: {value}",+ "callback_data": f"a0:policy:{field}:{action}:{_key(context, field)}"}])+ rows.append([{"text": "Use inherited policy", "callback_data": f"a0:policy:mode:inherit:{_key(context, 'mode')}"}])+ nav = []+ if page:+ nav.append({"text": "Prev", "callback_data": f"a0:{kind}page:{page - 1}"})+ if (page + 1) * 8 < len(items):+ nav.append({"text": "Next", "callback_data": f"a0:{kind}page:{page + 1}"})+ if nav:+ rows.append(nav)+ title += f"\nPage {page + 1}/{max(1, (len(items) + 7) // 8)}"+ await tc.raw_send_text(token, chat_id, title, message_id, None, {"inline_keyboard": rows})+++def _save_policy(context, policy):+ if context.config.profile == "default" or context.is_running():+ raise ValueError("Choose an editable profile and stop the active run before changing permissions.")+ plan = editor.build_change_plan({"profile_id": context.config.profile, "tool_policy": policy}, context)+ editor.apply_change_plan(plan)+++async def handle_callback(context, token, chat_id, message_id, action, value):+ actions = {"pluginspage", "permissionspage", "plugin", "tool", "toolset", "policy"}+ if action not in actions:+ return False+ if "_commands" not in plugins.get_enabled_plugins(context.agent0):+ raise ValueError("Commands is disabled for this chat.")+ if action in {"pluginspage", "permissionspage"}:+ await show(context, token, chat_id, message_id, action.removesuffix('page'), int(value))+ elif action == "plugin":+ desired, key = value.split(":", 1)+ if desired == 'noop':+ return True+ name, meta = next(((name, meta) for name, meta in _plugin_items() if _key(context, name) == key), (None, None))+ if not meta or meta.always_enabled or name in {"_telegram_integration", "_commands"} or desired not in {'on','off'}:+ raise ValueError("This plugin choice is unavailable. Send /plugins again.")+ plugins.toggle_plugin(name, desired == 'on')+ await show(context, token, chat_id, message_id, "plugins")+ elif action == "tool":+ item = next((item for item in tool_policy.get_tool_catalog(context.agent0) if _key(context, item['id']) == value), None)+ if not item:+ raise ValueError("This tool choice is no longer current. Send /permissions again.")+ await tc.raw_send_text(token, chat_id, item['label'] + "\n" + item.get('description', ''), message_id, None,+ {"inline_keyboard": [[{"text": label, "callback_data": f"a0:toolset:{choice}:{value}"}+ for choice, label in (("allow", "Allow"), ("block", "Block"), ("default", "Default"))]]})+ elif action == "toolset":+ desired, key = value.split(':', 1)+ item = next((item for item in tool_policy.get_tool_catalog(context.agent0) if _key(context, item['id']) == key), None)+ if not item or desired not in {'allow', 'block', 'default'}:+ raise ValueError("This tool choice is no longer current. Send /permissions again.")+ policy = tool_policy.get_policy(context.agent0)+ policy['mode'] = 'custom'+ for field in ('allowed', 'blocked'):+ policy[field] = [value for value in policy[field] if value != item['id']]+ if desired != 'default':+ policy['allowed' if desired == 'allow' else 'blocked'].append(item['id'])+ _save_policy(context, policy)+ await show(context, token, chat_id, message_id, 'permissions')+ elif action == "policy":+ field, desired, key = value.split(':', 2)+ if key != _key(context, field) or (field, desired) not in {+ ('mode', 'inherit'), ('default', 'allow'), ('default', 'block'), ('mcp_default', 'allow'), ('mcp_default', 'block')+ }:+ raise ValueError("This permission choice is no longer current. Send /permissions again.")+ policy = tool_policy.get_policy(context.agent0)+ policy.update(mode='custom')+ policy[field] = desired+ _save_policy(context, policy)+ await show(context, token, chat_id, message_id, 'permissions')+ return Truediff --git a/plugins/_telegram_integration/helpers/slash_commands.py b/plugins/_telegram_integration/helpers/slash_commands.pynew file mode 100644index 000000000..76fa4cc20--- /dev/null+++ b/plugins/_telegram_integration/helpers/slash_commands.py@@ -0,0 +1,266 @@+"""Resolve Agent Zero commands before Telegram adds its message envelope."""+from __future__ import annotations++import re+from copy import deepcopy++from agent import AgentContext+from helpers import integration_commands, plugins, projects+from helpers.persist_chat import save_tmp_chat+from plugins._commands.helpers import commands+from plugins._telegram_integration.helpers import command_ui, telegram_client as tc+++# These names retain Telegram's existing behavior and pickers for bundled commands.+PICKERS = {"models": "model", "presets": "model", "chats": "sessions", "chat": "sessions"}+++def available_commands(context=None) -> list[dict]:+ enabled = plugins.get_enabled_plugins(context.agent0 if context else None)+ if "_commands" not in enabled:+ return []+ project = projects.get_context_project_name(context) if context else ""+ return [item for item in commands.list_effective_commands(project or "")[0]+ if not item.get("source_plugin") or item["source_plugin"] in enabled]+++def menu_commands() -> list[tuple[str, str]]:+ menu = dict(integration_commands.telegram_menu_commands())+ menu["start"] = "Connect to Agent Zero."+ for item in available_commands():+ name = item["name"].replace("-", "_")+ if re.fullmatch(r"[a-z0-9_]{1,32}", name):+ menu.setdefault(name, str(item.get("description") or item["name"])[:256])+ return list(menu.items())[:100]+++async def reply(token, chat_id, message_id, text, markup=None):+ # Plain text avoids treating command output as Telegram HTML.+ for chunk in tc._split_text(str(text), tc.MAX_MESSAGE_LENGTH):+ await tc.raw_send_text(token, chat_id, chunk, message_id, None, markup)+ markup = None+++async def handle(context, token, chat_id, message_id, text) -> str | None:+ """Return agent input, or None when the command was handled without an LLM."""+ invocation = commands.parse_slash_invocation(text)+ name = invocation["command_name"]+ if not name:+ return text+ items = available_commands(context)+ item = next((c for c in items if c["name"] == name), None)+ if not item:+ item = next((c for c in items if c["name"].replace("-", "_") == name), None)+ args = invocation["raw_arguments"]+ name = item["name"] if item else name+ line = f"/{name} {args}".rstrip()+ custom = item and item.get("source_scope_key") != "builtin"+ try:+ if not custom:+ if name in {"commands", "help"}:+ await send_menu(context, token, chat_id, message_id)+ return None+ if name in PICKERS and (name != "chats" or not args):+ if name in {"models", "presets"} and args:+ result = integration_commands.try_handle_command(context, f"/model {args}", integration="telegram")+ await reply(token, chat_id, message_id, result or "Use /model to choose a preset.")+ return None+ if name == "chat" and args:+ target = AgentContext.get(args)+ if not target:+ raise ValueError("Chat not found. Use /sessions to choose a chat.")+ await select_session(context, target)+ await reply(token, chat_id, message_id, f"Switched to {target.name or target.id}.")+ else:+ await command_ui.handle_command(context, token, chat_id, message_id, f"/{PICKERS[name]}")+ return None+ # Keep Telegram reset semantics; /new below uses a fresh context.+ if (name != "new" or not item) and (name != "queue" or not item):+ if await command_ui.handle_command(context, token, chat_id, message_id, line):+ return None+ # /profile with arguments uses the shared command, including creation.+ if name != "profile" or not item:+ result = integration_commands.try_handle_command(context, line, integration="telegram")+ if result is not None:+ await reply(token, chat_id, message_id, result)+ return None+ if not item:+ if text.lstrip().startswith("/"):+ await reply(token, chat_id, message_id, f"Unknown command: /{name}. Use /commands to see commands for this chat.")+ return None+ return text+ resolution = await commands.resolve_command_invocation(+ path=item["path"], slash_text=line,+ project_name=projects.get_context_project_name(context) or "", context_id=context.id,+ )+ return await apply_result(context, token, chat_id, message_id, name, resolution["result"])+ except Exception as exc:+ await reply(token, chat_id, message_id, f"/{name} failed: {exc}")+ return None+++async def apply_result(context, token, chat_id, message_id, name, result):+ text = str(result.get("text") or "")+ notes = []+ for effect in result.get("effects") or []:+ if not isinstance(effect, dict):+ continue+ kind = str(effect.get("type") or "").lower()+ if kind in {"replace_input", "send_message"}:+ text = str(effect.get("text") or (text if kind == "send_message" else ""))+ elif kind == "append_input":+ text = "\n".join(filter(None, (text, str(effect.get("text") or ""))))+ elif kind in {"toast", "show_markdown"}:+ notes.append(str(effect.get("message" if kind == "toast" else "content") or ""))+ elif kind == "goal_changed":+ pass+ elif kind == "new_chat":+ target = AgentContext(deepcopy(context.config))+ command_ui._copy_telegram_binding(context, target)+ for key in ("telegram_bot_cfg", "telegram_stream_enabled", "telegram_tools_enabled", "chat_model_override"):+ if key in context.data:+ target.data[key] = deepcopy(context.data[key])+ project = projects.get_context_project_name(context)+ if project:+ projects.activate_project(target.id, project)+ command_ui._set_session_mapping(target)+ save_tmp_chat(target)+ elif kind == "select_chat":+ target = AgentContext.get(str(effect.get("context_id") or ""))+ if not target:+ raise ValueError("Chat not found.")+ await select_session(context, target)+ elif kind in {"pause_agent", "nudge_agent"}:+ action = "nudge" if kind == "nudge_agent" else ("pause" if effect.get("paused") else "resume")+ notes.append(integration_commands.try_handle_command(context, f"/{action}", integration="telegram") or "")+ elif kind in {"reset_chat", "clear_transcript"}:+ notes.append(integration_commands.try_handle_command(context, "/clear", integration="telegram") or "")+ elif kind == "compact_chat":+ await compact_menu(context, token, chat_id, message_id)+ elif kind == "attach_files":+ notes.append("Use Telegram's attachment button to send photos or files, with an optional command in the caption.")+ elif kind == "copy_transcript":+ from aiogram import Bot+ from aiogram.types import BufferedInputFile+ from helpers.history import output_text+ transcript = output_text(context.agent0.history.output(), ai_label="assistant", human_label="user")+ if not transcript:+ notes.append("This chat has no transcript yet.")+ else:+ async with Bot(token) as bot:+ await bot.send_document(chat_id, BufferedInputFile(transcript.encode("utf-8"), filename="transcript.txt"))+ elif kind == "computer_use":+ notes.append(str(effect.get("fallback") or "Use Host access in A0 Launcher to change computer permissions."))+ elif kind == "test_agent_profile":+ notes.append(integration_commands.try_handle_command(context, f"/agent {effect.get('profile_id', '')}", integration="telegram") or "")+ elif kind == "open_modal" and effect.get("path") == "/components/projects/project-list.html":+ await command_ui.send_project_picker(context, token, chat_id, message_id, 0)+ elif kind == "open_modal" and effect.get("path") == "/plugins/_model_config/webui/main.html":+ await command_ui.send_model_picker(context, token, chat_id, message_id, 0)+ elif kind == "open_agent_editor" and effect.get("view") == "manage":+ await command_ui.send_agent_picker(context, token, chat_id, message_id, 0)+ elif kind == "open_modal" and effect.get("path") == "/plugins/_browser/webui/main.html":+ await reply(token, chat_id, message_id, "Browser runtime", {"inline_keyboard": [[+ {"text": label, "callback_data": f"a0:run:browser {action}"}+ for label, action in (("Status", "status"), ("Docker", "container"), ("Host", "host"))+ ]]})+ elif kind in {"open_modal", "open_plugin_config", "open_agent_editor"}:+ if name in {"plugins", "permissions"}:+ from plugins._telegram_integration.helpers import settings_ui+ await settings_ui.show(context, token, chat_id, message_id, name)+ else:+ notes.append(f"Open /{name} in the Agent Zero WebUI to edit these settings.")+ else:+ notes.append(f"/{name}: the '{kind}' action requires the Agent Zero WebUI.")+ if notes:+ await reply(token, chat_id, message_id, "\n\n".join(filter(None, notes)))+ elif not text.strip() and not result.get("effects"):+ await reply(token, chat_id, message_id, f"/{name} complete.")+ return text if text.strip() else None+++async def select_session(context, target):+ if context.is_running() or target.is_running():+ raise ValueError("Stop the active run before switching sessions.")+ command_ui._copy_telegram_binding(context, target)+ command_ui._set_session_mapping(target)+ save_tmp_chat(target)+++async def send_menu(context, token, chat_id, message_id, page=0):+ catalog = {c["name"]: (c.get("description", ""), c.get("argument_hint", "")) for c in available_commands(context)}+ for command in integration_commands.COMMAND_REGISTRY:+ if integration_commands.resolve_command(command.name, integration="telegram"):+ catalog.setdefault(command.name, (command.description, command.args_hint))+ items = sorted(catalog.items())+ page = min(max(0, page), max(0, (len(items) - 1) // 8))+ lines = [f"Commands for this chat ({page + 1}/{max(1, (len(items) + 7) // 8)})"]+ rows = []+ for name, (description, hint) in items[page * 8:page * 8 + 8]:+ lines.append(f"/{name}{' ' + hint if hint else ''} — {description}")+ callback = f"a0:command:{name}"+ if len(callback.encode()) <= 64:+ rows.append([{"text": f"/{name}", "callback_data": callback}])+ nav = []+ if page:+ nav.append({"text": "Prev", "callback_data": f"a0:page:{page - 1}"})+ if (page + 1) * 8 < len(items):+ nav.append({"text": "Next", "callback_data": f"a0:page:{page + 1}"})+ if nav:+ rows.append(nav)+ await reply(token, chat_id, message_id, "\n\n".join(lines), {"inline_keyboard": rows})+++async def compact_menu(context, token, chat_id, message_id):+ from plugins._chat_compaction.helpers.compactor import MIN_COMPACTION_TOKENS, get_compaction_stats+ if "_chat_compaction" not in plugins.get_enabled_plugins(context.agent0):+ raise ValueError("Chat Compaction is disabled for this chat.")+ if context.is_running():+ raise ValueError("Stop the active run before compacting.")+ stats = await get_compaction_stats(context)+ if stats["token_count"] < MIN_COMPACTION_TOKENS:+ raise ValueError(f"Not enough content to compact (minimum {MIN_COMPACTION_TOKENS:,} tokens).")+ await reply(token, chat_id, message_id,+ f"Compact {stats['message_count']} messages (~{stats['token_count']:,} tokens)? The original conversation will be backed up.",+ {"inline_keyboard": [[{"text": "Compact", "callback_data": f"a0:compact:{context.id}"}]]})+++async def handle_callback(context, token, chat_id, message_id, data):+ """Return (handled, agent text) for command menu callbacks."""+ if not data.startswith("a0:"):+ return False, None+ _, action, value = data.split(":", 2)+ from plugins._telegram_integration.helpers import settings_ui+ if await settings_ui.handle_callback(context, token, chat_id, message_id, action, value):+ return True, None+ if action == "page":+ await send_menu(context, token, chat_id, message_id, int(value))+ elif action == "command":+ items = available_commands(context)+ item = next((item for item in items if item["name"] == value), None)+ definition = integration_commands.resolve_command(value, integration="telegram")+ if not item and not definition:+ raise ValueError("This command is no longer available. Send /commands again.")+ hint = item.get("argument_hint", "") if item else (definition.args_hint if definition else "")+ # Selecting a command shows its usage; a separate Run button is explicit.+ await reply(token, chat_id, message_id, f"/{value}{' ' + hint if hint else ''}\nSend this command with any arguments, or run it now.",+ {"inline_keyboard": [[{"text": f"Run /{value}", "callback_data": f"a0:run:{value}"}]]})+ elif action == "run":+ return True, await handle(context, token, chat_id, message_id, f"/{value}")+ elif action == "compact":+ if value != context.id or context.is_running():+ raise ValueError("This confirmation is no longer current. Send /compact again.")+ if "_chat_compaction" not in plugins.get_enabled_plugins(context.agent0):+ raise ValueError("Chat Compaction is disabled for this chat.")+ await reply(token, chat_id, message_id, "Compacting chat…")+ context.run_task(_compact, context, token, chat_id, message_id)+ return True, None+++async def _compact(context, token, chat_id, message_id):+ from plugins._chat_compaction.helpers.compactor import run_compaction+ try:+ await run_compaction(context)+ await reply(token, chat_id, message_id, "Chat compacted. The original conversation was backed up.")+ except Exception as exc:+ await reply(token, chat_id, message_id, f"Compaction failed: {exc}")diff --git a/plugins/_telegram_integration/hooks.py b/plugins/_telegram_integration/hooks.pynew file mode 100644index 000000000..6a4d481eb--- /dev/null+++ b/plugins/_telegram_integration/hooks.py@@ -0,0 +1,20 @@+from copy import deepcopy+from hashlib import sha256+++def get_plugin_config(default=None, **kwargs):+ config = deepcopy(default or {})+ for bot in config.get("bots", []):+ bot["token"] = str(bot.get("token") or "").strip()+ if not str(bot.get("name") or "").strip() and bot["token"]:+ bot_id = bot["token"].split(":", 1)[0]+ bot["name"] = "bot_" + (bot_id if bot_id.isdigit() else sha256(bot["token"].encode()).hexdigest()[:12])+ return config+++def save_plugin_config(settings=None, **kwargs):+ config = get_plugin_config(settings)+ names = [bot.get("name") for bot in config.get("bots", []) if bot.get("name")]+ if len(names) != len(set(names)):+ raise ValueError("Each Telegram bot must have a different name.")+ return configdiff --git a/plugins/_telegram_integration/prompts/fw.telegram.user_message.md b/plugins/_telegram_integration/prompts/fw.telegram.user_message.mdindex a05af6818..969bbfce6 100644--- a/plugins/_telegram_integration/prompts/fw.telegram.user_message.md+++ b/plugins/_telegram_integration/prompts/fw.telegram.user_message.md@@ -1,3 +1,5 @@[Telegram message from {{sender}}]-{{body}}\ No newline at end of file+{{body}}++[End Telegram message]diff --git a/plugins/_telegram_integration/webui/config.html b/plugins/_telegram_integration/webui/config.htmlindex 1ba6c0e65..ca22c3a91 100644--- a/plugins/_telegram_integration/webui/config.html+++ b/plugins/_telegram_integration/webui/config.html@@ -113,7 +113,7 @@<div class="field"><div class="field-label"><div class="field-title">Bot name</div>- <div class="field-description">A friendly internal label so you can tell bots apart.</div>+ <div class="field-description">An internal label to tell bots apart. Leave empty to generate one automatically.</div></div><div class="field-control"><input type="text" x-model="bot.name" placeholder="support_bot" />diff --git a/tests/test_telegram_commands.py b/tests/test_telegram_commands.pynew file mode 100644index 000000000..7242aa579--- /dev/null+++ b/tests/test_telegram_commands.py@@ -0,0 +1,185 @@+import asyncio+import importlib+import tempfile+import unittest+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import AsyncMock, patch++from aiogram.types import Update++from plugins._commands.helpers import commands+from plugins._telegram_integration import hooks+from plugins._telegram_integration.helpers import bot_manager, handler, slash_commands as slash+++class TelegramCommandsTests(unittest.TestCase):+ def test_config_names_and_connection_changes(self):+ config = {"bots": [{"name": "", "token": " 123456:secret ", "enabled": True}]}+ normalized = hooks.get_plugin_config(config)+ self.assertEqual(normalized["bots"][0]["name"], "bot_123456")+ self.assertEqual(normalized["bots"][0]["token"], "123456:secret")+ self.assertEqual(config["bots"][0]["name"], "")+ self.assertEqual(hooks.save_plugin_config(normalized), normalized)+ with self.assertRaises(ValueError):+ hooks.save_plugin_config({"bots": normalized["bots"] * 2})+ self.assertNotIn("secret", hooks.get_plugin_config({"bots": [{"token": "secret"}]})["bots"][0]["name"])++ manager = importlib.import_module("plugins._telegram_integration.extensions.python.job_loop._10_telegram_bot")+ current = SimpleNamespace(bot=SimpleNamespace(token="old"), webhook_active=False,+ group_mode="mention", task=SimpleNamespace(done=lambda: False))+ replacement = SimpleNamespace()+ async def check():+ with patch.object(manager.plugins, "get_plugin_config", return_value=normalized), \+ patch.object(manager, "ensure_dependencies"), \+ patch.object(handler, "cleanup_old_attachments"), \+ patch.object(bot_manager, "get_all_bots", return_value={"bot_123456": current}), \+ patch.object(bot_manager, "stop_bot", new_callable=AsyncMock) as stop, \+ patch.object(bot_manager, "create_bot", return_value=replacement), \+ patch.object(bot_manager, "cache_bot_info", new_callable=AsyncMock), \+ patch.object(bot_manager, "register_bot_commands", new_callable=AsyncMock), \+ patch.object(bot_manager, "start_polling", new_callable=AsyncMock) as start:+ await manager.TelegramBotManager(agent=None).execute()+ stop.assert_awaited_once_with("bot_123456")+ start.assert_awaited_once_with(replacement)+ stop.reset_mock()+ current.bot.token = "123456:secret"+ await manager.TelegramBotManager(agent=None).execute()+ stop.assert_not_awaited()+ asyncio.run(check())++ def test_shared_commands_and_telegram_effects(self):+ ctx = SimpleNamespace(id="test-context", agent0=SimpleNamespace(), is_running=lambda: False)+ async def check(root):+ scope = root / "commands"+ scope.mkdir()+ (scope / "summarize.command.yaml").write_text(+ 'name: summarize\ndescription: Summarize input\ntype: text\ntemplate_path: summarize.txt\n')+ (scope / "summarize.txt").write_text('Summarize: {raw}')+ (scope / "stop.command.yaml").write_text(+ 'name: stop\ndescription: Custom stop\ntype: text\ntemplate_path: stop.txt\n')+ (scope / "stop.txt").write_text('Override: {raw}')+ with patch.object(commands, "get_scope_directory", return_value=str(scope)), \+ patch.object(commands, "_iter_precedence_scopes", return_value=[""]), \+ patch.object(commands, "get_scope_payload", return_value={}), \+ patch.object(commands, "_discover_plugin_commands", return_value=[]), \+ patch.object(commands, "_get_context", return_value=ctx), \+ patch.object(slash.AgentContext, "get", return_value=ctx), \+ patch.object(slash.projects, "get_context_project_name", return_value=""), \+ patch.object(slash.plugins, "get_enabled_plugins", return_value=["_commands"]), \+ patch.object(slash, "reply", new_callable=AsyncMock) as reply, \+ patch.object(slash.command_ui, "handle_command", new_callable=AsyncMock, return_value=False):+ self.assertEqual(await slash.handle(ctx, "token", 1, 2, "/summarize hello\nworld"), "Summarize: hello\nworld")+ self.assertEqual(await slash.handle(ctx, "token", 1, 2, "hello /summarize"), "Summarize: hello")+ self.assertEqual(await slash.handle(ctx, "token", 1, 2, "/stop custom"), "Override: custom")+ self.assertEqual(await slash.handle(ctx, "token", 1, 2, "Read /a0/file"), "Read /a0/file")+ self.assertIsNone(await slash.handle(ctx, "token", 1, 2, "/missing"))+ self.assertIn("Unknown command", reply.call_args.args[3])+ scope.joinpath("stop.command.yaml").unlink()+ with patch("api.stop.stop_context", return_value={"message": "Stopped."}) as stop:+ self.assertIsNone(await slash.handle(ctx, "token", 1, 2, "/stop"))+ stop.assert_called_once_with(ctx)+ self.assertEqual(reply.call_args.args[3], "Stopped.")+ self.assertIsNone(await slash.handle(ctx, "token", 1, 2, "/attach"))+ self.assertIn("attachment button", reply.call_args.args[3])+ await slash.send_menu(ctx, "token", 1, 2)+ markup = reply.call_args.args[4]+ self.assertTrue(all(len(button["callback_data"].encode()) <= 64 for row in markup["inline_keyboard"] for button in row))+ names = dict(slash.menu_commands())+ self.assertIn("computer_use", names)+ self.assertIn("summarize", names)+ self.assertTrue(all(len(name) <= 32 and "-" not in name for name in names))+ handled, text = await slash.handle_callback(ctx, "token", 1, 2, "a0:run:summarize example")+ self.assertTrue(handled)+ self.assertEqual(text, "Summarize: example")+ ctx.is_running = lambda: True+ with self.assertRaises(ValueError):+ await slash.handle_callback(ctx, "token", 1, 2, "a0:compact:test-context")+ with self.assertRaises(ValueError):+ await slash.select_session(ctx, ctx)+ result = await slash.apply_result(ctx, "token", 1, 2, "goal", {+ "effects": [{"type": "goal_changed"}, {"type": "toast", "message": "Goal set."},+ {"type": "send_message", "text": "Objective"}]})+ self.assertEqual(result, "Objective")+ self.assertEqual(reply.call_args.args[3], "Goal set.")+ self.assertIsNone(await slash.apply_result(ctx, "token", 1, 2, "empty", {}))+ self.assertEqual(reply.call_args.args[3], "/empty complete.")+ with tempfile.TemporaryDirectory() as directory:+ asyncio.run(check(Path(directory)))++ def test_settings_menus_validate_scope_and_use_existing_owners(self):+ from plugins._telegram_integration.helpers import settings_ui as ui+ ctx = SimpleNamespace(id="ctx", config=SimpleNamespace(profile="agent0"),+ agent0=SimpleNamespace(), is_running=lambda: False)+ item = {"id": "core:test", "name": "test", "label": "Test tool", "description": ""}+ policy = {"mode": "custom", "default": "allow", "mcp_default": "block", "allowed": [], "blocked": []}+ meta = SimpleNamespace(title="Test plugin", always_enabled=False)+ async def check():+ with patch.object(ui.projects, "get_context_project_name", return_value="project"), \+ patch.object(ui.plugins, "get_enabled_plugins", return_value=["_commands"]), \+ patch.object(ui.tool_policy, "get_tool_catalog", return_value=[item]), \+ patch.object(ui.tool_policy, "get_policy", side_effect=lambda agent: dict(policy)), \+ patch.object(ui.tc, "raw_send_text", new_callable=AsyncMock) as send, \+ patch.object(ui.editor, "build_change_plan", return_value="plan") as build, \+ patch.object(ui.editor, "apply_change_plan") as apply, \+ patch.object(ui, "_plugin_items", return_value=[("example", meta)]), \+ patch.object(ui.plugins, "get_toggle_state", return_value="disabled"), \+ patch.object(ui.plugins, "toggle_plugin") as toggle:+ await ui.show(ctx, "token", 1, 2, "permissions")+ for row in send.call_args.args[5]["inline_keyboard"]:+ for button in row:+ self.assertLessEqual(len(button['callback_data'].encode()), 64)+ key = ui._key(ctx, item['id'])+ await ui.handle_callback(ctx, "token", 1, 2, "toolset", "block:" + key)+ patch_data = build.call_args.args[0]+ self.assertEqual(patch_data['tool_policy']['blocked'], ['core:test'])+ self.assertEqual(patch_data['tool_policy']['mcp_default'], 'block')+ apply.assert_called_once_with('plan')+ ctx.config.profile = 'other'+ with self.assertRaises(ValueError):+ await ui.handle_callback(ctx, "token", 1, 2, "toolset", "allow:" + key)+ ctx.config.profile = 'agent0'+ ctx.is_running = lambda: True+ with self.assertRaises(ValueError):+ await ui.handle_callback(ctx, "token", 1, 2, "toolset", "allow:" + key)+ ctx.is_running = lambda: False+ await ui.handle_callback(ctx, "token", 1, 2, "plugin", 'on:' + ui._key(ctx, 'example'))+ toggle.assert_called_once_with('example', True)+ meta.always_enabled = True+ with self.assertRaises(ValueError):+ await ui.handle_callback(ctx, "token", 1, 2, "plugin", 'off:' + ui._key(ctx, 'example'))+ with self.assertRaises(ValueError):+ await ui.handle_callback(ctx, "token", 1, 2, "toolset", 'block:' + ui._key(ctx, 'core:response'))+ asyncio.run(check())++ def test_real_dispatch_and_bot_suffix(self):+ instance = SimpleNamespace(bot_info=SimpleNamespace(username="OurBot"))+ self.assertEqual(handler._normalize_bot_command("/goal@ourbot multi\nline", instance), "/goal multi\nline")+ self.assertIsNone(handler._normalize_bot_command("/goal@otherbot test", instance))+ template = (Path(__file__).resolve().parents[1] / "plugins/_telegram_integration/prompts/fw.telegram.user_message.md").read_text()+ envelope = template.replace("{{sender}}", "Tester").replace("{{body}}", "literal /goal")+ self.assertEqual(commands.parse_slash_invocation(envelope)["command_name"], "")+ async def check():+ received = []+ async def receive(message):+ received.append(message.text)+ with patch.object(bot_manager, "_bots", {}):+ bot = bot_manager.create_bot("test", "123456:test", receive, receive,+ on_command_control=receive, group_mode="off")+ try:+ for chat_type, text in [("group", "/status"), ("group", "/start"), ("private", "/goal test")]:+ update = Update.model_validate({"update_id": 1, "message": {+ "message_id": 1, "date": 1700000000, "text": text,+ "from": {"id": 42, "is_bot": False, "first_name": "Test"},+ "chat": {"id": 42, "type": chat_type},+ "entities": [{"type": "bot_command", "offset": 0, "length": len(text.split()[0])}],+ }})+ await bot.dispatcher.feed_update(bot.bot, update)+ self.assertEqual(received, ["/goal test"])+ finally:+ await bot.bot.session.close()+ asyncio.run(check())+++if __name__ == "__main__":+ unittest.main()