Agent Zero AI framework
Add Telegram long-run status updates
Anmol Malik99207d60a2ce
diff --git a/plugins/_telegram_integration/extensions/python/_functions/agent/Agent/handle_exception/end/_85_telegram_error.py b/plugins/_telegram_integration/extensions/python/_functions/agent/Agent/handle_exception/end/_85_telegram_error.pyindex 443df0d74..b711ba350 100644--- a/plugins/_telegram_integration/extensions/python/_functions/agent/Agent/handle_exception/end/_85_telegram_error.py+++ b/plugins/_telegram_integration/extensions/python/_functions/agent/Agent/handle_exception/end/_85_telegram_error.py@@ -27,7 +27,7 @@ class TelegramFriendlyError(Extension):context.data[CTX_TG_ERROR_SENT] = True- from plugins._telegram_integration.helpers import draft_stream, error_ui+ from plugins._telegram_integration.helpers import draft_stream, error_ui, heartbeatfrom plugins._telegram_integration.helpers.handler import send_telegram_replytext = error_ui.friendly_error_message(exception)@@ -38,5 +38,6 @@ class TelegramFriendlyError(Extension):typing_stop = context.data.pop(CTX_TG_TYPING_STOP, None)if typing_stop:typing_stop.set()+ await heartbeat.stop(context)draft_stream.clear(context)context.data.pop(CTX_TG_REPLY_TO, None)diff --git a/plugins/_telegram_integration/extensions/python/message_loop_start/_45_telegram_draft_start.py b/plugins/_telegram_integration/extensions/python/message_loop_start/_45_telegram_draft_start.pyindex af773207d..6fc4fe89c 100644--- a/plugins/_telegram_integration/extensions/python/message_loop_start/_45_telegram_draft_start.py+++ b/plugins/_telegram_integration/extensions/python/message_loop_start/_45_telegram_draft_start.py@@ -12,6 +12,7 @@ class TelegramDraftStart(Extension):if not context.data.get(CTX_TG_BOT):return- from plugins._telegram_integration.helpers import draft_stream+ from plugins._telegram_integration.helpers import draft_stream, heartbeatawait draft_stream.start(context)+ await heartbeat.start(context)diff --git a/plugins/_telegram_integration/extensions/python/process_chain_end/_55_telegram_reply.py b/plugins/_telegram_integration/extensions/python/process_chain_end/_55_telegram_reply.pyindex dcd28665e..508c3acf4 100644--- a/plugins/_telegram_integration/extensions/python/process_chain_end/_55_telegram_reply.py+++ b/plugins/_telegram_integration/extensions/python/process_chain_end/_55_telegram_reply.py@@ -26,14 +26,13 @@ class TelegramAutoReply(Extension):returnresponse_text = _extract_last_response(context)- if not response_text:- returnattachments = context.data.pop(CTX_TG_ATTACHMENTS, [])keyboard = context.data.pop(CTX_TG_KEYBOARD, None)try:- await self._send_reply(context, response_text, attachments, keyboard)+ if response_text:+ await self._send_reply(context, response_text, attachments, keyboard)except Exception as e:PrintStyle.error(f"Telegram auto-reply error: {format_error(e)}")finally:@@ -41,8 +40,9 @@ class TelegramAutoReply(Extension):typing_stop = context.data.pop(CTX_TG_TYPING_STOP, None)if typing_stop:typing_stop.set()- from plugins._telegram_integration.helpers import draft_stream+ from plugins._telegram_integration.helpers import draft_stream, heartbeat+ await heartbeat.stop(context)draft_stream.clear(context)context.data.pop(CTX_TG_REPLY_TO, None)diff --git a/plugins/_telegram_integration/helpers/constants.py b/plugins/_telegram_integration/helpers/constants.pyindex 1ef80c81a..190ee7fa4 100644--- a/plugins/_telegram_integration/helpers/constants.py+++ b/plugins/_telegram_integration/helpers/constants.py@@ -23,3 +23,5 @@ CTX_TG_RESPONSE_MESSAGE_ID = "_telegram_response_message_id"CTX_TG_RESPONSE_TEXT = "_telegram_response_text"CTX_TG_RESPONSE_LAST_UPDATE = "_telegram_response_last_update"CTX_TG_ERROR_SENT = "_telegram_error_sent"+CTX_TG_HEARTBEAT_TASK = "_telegram_heartbeat_task"+CTX_TG_HEARTBEAT_STOP = "_telegram_heartbeat_stop"diff --git a/plugins/_telegram_integration/helpers/heartbeat.py b/plugins/_telegram_integration/helpers/heartbeat.pynew file mode 100644index 000000000..188127e41--- /dev/null+++ b/plugins/_telegram_integration/helpers/heartbeat.py@@ -0,0 +1,101 @@+from __future__ import annotations++import asyncio+import re+import time+from contextlib import suppress++from agent import AgentContext+from helpers.print_style import PrintStyle+from plugins._telegram_integration.helpers import telegram_client as tc+from plugins._telegram_integration.helpers.bot_manager import get_bot+from plugins._telegram_integration.helpers.constants import (+ CTX_TG_BOT,+ CTX_TG_CHAT_ID,+ CTX_TG_HEARTBEAT_STOP,+ CTX_TG_HEARTBEAT_TASK,+)+++HEARTBEAT_INTERVAL_SECONDS = 180+++async def start(context: AgentContext) -> None:+ task = context.data.get(CTX_TG_HEARTBEAT_TASK)+ if task and not task.done():+ return++ stop_event = asyncio.Event()+ context.data[CTX_TG_HEARTBEAT_STOP] = stop_event+ context.data[CTX_TG_HEARTBEAT_TASK] = asyncio.create_task(+ _heartbeat_loop(context, stop_event, time.monotonic())+ )+++async def stop(context: AgentContext) -> None:+ stop_event = context.data.pop(CTX_TG_HEARTBEAT_STOP, None)+ if stop_event:+ stop_event.set()++ task = context.data.pop(CTX_TG_HEARTBEAT_TASK, None)+ if task and not task.done():+ task.cancel()+ with suppress(asyncio.CancelledError):+ await task+++async def _heartbeat_loop(+ context: AgentContext,+ stop_event: asyncio.Event,+ started_at: float,+) -> None:+ try:+ while True:+ try:+ await asyncio.wait_for(stop_event.wait(), timeout=HEARTBEAT_INTERVAL_SECONDS)+ return+ except asyncio.TimeoutError:+ await _send_heartbeat(context, time.monotonic() - started_at)+ except asyncio.CancelledError:+ raise+ except Exception as exc:+ PrintStyle.debug(f"Telegram heartbeat stopped: {exc}")+++async def _send_heartbeat(context: AgentContext, elapsed_seconds: float) -> bool:+ bot_name = context.data.get(CTX_TG_BOT)+ chat_id = context.data.get(CTX_TG_CHAT_ID)+ bot = get_bot(bot_name) if bot_name else None+ if not bot or not chat_id:+ return False++ text = heartbeat_text(elapsed_seconds, _current_reason(context))+ sent_id = await tc.raw_send_text(+ bot.bot.token,+ int(chat_id),+ text,+ parse_mode=None,+ )+ return bool(sent_id)+++def heartbeat_text(elapsed_seconds: float, reason: str = "") -> str:+ minutes = max(1, int(round(elapsed_seconds / 60)))+ detail = reason or "working on your request"+ return f"Still working... ({minutes} min elapsed - {detail})"+++def _current_reason(context: AgentContext) -> str:+ progress = str(getattr(getattr(context, "log", None), "progress", "") or "")+ progress = _clean_progress(progress)+ if not progress or progress.lower() == "waiting for input":+ return "working on your request"+ return progress+++def _clean_progress(text: str) -> str:+ value = re.sub(r"icon://[a-zA-Z0-9_]+(?:\[[^\]]*\])?\s*", "", text)+ value = re.sub(r"\s+", " ", value).strip()+ if len(value) > 80:+ value = f"{value[:77].rstrip()}..."+ return valuediff --git a/tests/test_telegram_heartbeat.py b/tests/test_telegram_heartbeat.pynew file mode 100644index 000000000..e9626ed42--- /dev/null+++ b/tests/test_telegram_heartbeat.py@@ -0,0 +1,71 @@+import asyncio++from plugins._telegram_integration.helpers import heartbeat+from plugins._telegram_integration.helpers.constants import (+ CTX_TG_BOT,+ CTX_TG_CHAT_ID,+ CTX_TG_HEARTBEAT_STOP,+ CTX_TG_HEARTBEAT_TASK,+)+++class FakeBot:+ class Bot:+ token = "token"++ bot = Bot()+++class FakeLog:+ progress = "icon://search[Search] A0: Searching official docs"+++class FakeContext:+ def __init__(self):+ self.data = {+ CTX_TG_BOT: "main",+ CTX_TG_CHAT_ID: 123,+ }+ self.log = FakeLog()+++def test_heartbeat_text_omits_iteration_count():+ text = heartbeat.heartbeat_text(180, "waiting for provider response")++ assert text == "Still working... (3 min elapsed - waiting for provider response)"+ assert "iteration" not in text+++def test_heartbeat_sends_periodic_status_and_stops(monkeypatch):+ calls = []++ async def fake_send(token, chat_id, text, parse_mode=None, **kwargs):+ calls.append(+ {+ "token": token,+ "chat_id": chat_id,+ "text": text,+ "parse_mode": parse_mode,+ }+ )+ return len(calls)++ context = FakeContext()+ monkeypatch.setattr(heartbeat, "HEARTBEAT_INTERVAL_SECONDS", 0.01)+ monkeypatch.setattr(heartbeat, "get_bot", lambda name: FakeBot())+ monkeypatch.setattr(heartbeat.tc, "raw_send_text", fake_send)++ async def run():+ await heartbeat.start(context)+ await asyncio.sleep(0.025)+ await heartbeat.stop(context)++ asyncio.run(run())++ assert calls+ assert calls[0]["chat_id"] == 123+ assert calls[0]["parse_mode"] is None+ assert "Still working..." in calls[0]["text"]+ assert "A0: Searching official docs" in calls[0]["text"]+ assert CTX_TG_HEARTBEAT_TASK not in context.data+ assert CTX_TG_HEARTBEAT_STOP not in context.data