From 9494b91308901a3a2171aaf18dbe64ca70f0bf0e Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sat, 20 Jun 2026 02:03:57 -0700 Subject: [PATCH 01/48] feat(talon): add Telegram channel adapter, CLI wiring, and offset persistence MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implements a pure-Python Telegram Bot API channel adapter for the talon host, following the same patterns as the existing WhatsApp channel. **Telegram channel adapter** (): - with env-var mapping ( prefix) and alias - using — no bridge subprocess needed - Long-polling via with configurable timeout and interval - MarkdownV2 message formatting with automatic plain-text fallback - for images, for other media types - typing indicator - for inbound media downloads - Operator auto-capture from first inbound message - Configurable exposure modes (default, allowlist, open) **Offset persistence** (ticket 23): - in the session directory - Atomic writes via - Loads persisted offset on startup, saves after each polling cycle - Graceful handling of missing/corrupt/invalid offset files **CLI wiring** (): - flag to enable the Telegram channel - Updated factory to accept both and - Both channels can coexist simultaneously **Config** (): - Added to - Added to for alias capture **Tests**: - 36 unit tests covering config, MarkdownV2 escaping, polling, exposure, outbound text/media, edit, typing, inbound media, status, offset persistence - 7 integration tests for factory and simultaneous channel coexistence Closes #21, #22, #23 --- libs/talon/deepagents_talon/__main__.py | 28 +- .../deepagents_talon/channels/__init__.py | 6 + .../deepagents_talon/channels/telegram.py | 776 +++++++++++++++++ libs/talon/deepagents_talon/config.py | 4 +- libs/talon/tests/channels/test_telegram.py | 780 ++++++++++++++++++ .../integration_tests/test_telegram_host.py | 198 +++++ 6 files changed, 1785 insertions(+), 7 deletions(-) create mode 100644 libs/talon/deepagents_talon/channels/telegram.py create mode 100644 libs/talon/tests/channels/test_telegram.py create mode 100644 libs/talon/tests/integration_tests/test_telegram_host.py diff --git a/libs/talon/deepagents_talon/__main__.py b/libs/talon/deepagents_talon/__main__.py index 23d864835bb..7ae24109069 100644 --- a/libs/talon/deepagents_talon/__main__.py +++ b/libs/talon/deepagents_talon/__main__.py @@ -13,6 +13,7 @@ import sys from typing import TYPE_CHECKING +from deepagents_talon.channels.telegram import TelegramChannel, TelegramChannelConfig from deepagents_talon.channels.whatsapp import WhatsAppChannel, WhatsAppChannelConfig from deepagents_talon.config import TalonConfig from deepagents_talon.cron import CronJobStore, PersistentCronScheduler @@ -49,6 +50,11 @@ def main() -> None: action="store_true", help="Attach the WhatsApp channel adapter.", ) + parser.add_argument( + "--telegram", + action="store_true", + help="Attach the Telegram channel adapter.", + ) subparsers = parser.add_subparsers(dest="command") _add_mcp_parsers(subparsers) args = parser.parse_args() @@ -64,7 +70,7 @@ def main() -> None: config.ensure_home() cleanup_sensitive_state(config=config, cron_store=cron_store) - channels = _channels(config, enabled=args.whatsapp) + channels = _channels(config, whatsapp=args.whatsapp, telegram=args.telegram) host = TalonHost( config=config, agent=asyncio.run(_agent_runtime(config, cron_store)), @@ -186,14 +192,26 @@ async def _run_once(host: TalonHost) -> None: await host.stop() -def _channels(config: TalonConfig, *, enabled: bool) -> tuple[ChannelAdapter, ...]: - if not enabled and config.env.get("DEEPAGENTS_TALON_WHATSAPP_ENABLED", "").lower() not in { +def _channels( + config: TalonConfig, + *, + whatsapp: bool = False, + telegram: bool = False, +) -> tuple[ChannelAdapter, ...]: + channels: list[ChannelAdapter] = [] + if whatsapp or config.env.get("DEEPAGENTS_TALON_WHATSAPP_ENABLED", "").lower() in { + "1", + "true", + "yes", + }: + channels.append(WhatsAppChannel(WhatsAppChannelConfig.from_talon_config(config))) + if telegram or config.env.get("DEEPAGENTS_TALON_TELEGRAM_ENABLED", "").lower() in { "1", "true", "yes", }: - return () - return (WhatsAppChannel(WhatsAppChannelConfig.from_talon_config(config)),) + channels.append(TelegramChannel(TelegramChannelConfig.from_talon_config(config))) + return tuple(channels) def _runtime_env(config: TalonConfig) -> dict[str, str]: diff --git a/libs/talon/deepagents_talon/channels/__init__.py b/libs/talon/deepagents_talon/channels/__init__.py index 0a9e01f041c..0a67d1f629f 100644 --- a/libs/talon/deepagents_talon/channels/__init__.py +++ b/libs/talon/deepagents_talon/channels/__init__.py @@ -11,11 +11,17 @@ format_markdown_for_channel, validate_media, ) +from deepagents_talon.channels.telegram import TelegramChannel, TelegramChannelConfig +from deepagents_talon.channels.whatsapp import WhatsAppChannel, WhatsAppChannelConfig __all__ = [ "ChannelExposure", "ChannelMediaError", "ExposureMode", + "TelegramChannel", + "TelegramChannelConfig", + "WhatsAppChannel", + "WhatsAppChannelConfig", "chunk_text", "format_markdown_for_channel", "validate_media", diff --git a/libs/talon/deepagents_talon/channels/telegram.py b/libs/talon/deepagents_talon/channels/telegram.py new file mode 100644 index 00000000000..bf1002294a7 --- /dev/null +++ b/libs/talon/deepagents_talon/channels/telegram.py @@ -0,0 +1,776 @@ +"""Telegram channel adapter backed by the Bot API over urllib. + +Talon is an experimental runtime and is subject to change or removal at any time. +""" + +from __future__ import annotations + +import asyncio +import json +import logging +import re +import urllib.error +import urllib.parse +import urllib.request +from dataclasses import dataclass, field +from pathlib import Path +from typing import TYPE_CHECKING, cast + +from deepagents_talon.channels.base import ( + MAX_TEXT_CHARS, + ChannelExposure, + ChannelMediaError, + ExposureMode, + chunk_text, + validate_media, +) +from deepagents_talon.interfaces import ChannelMedia, ChannelMessage, ChannelStatus, MessageHandler + +if TYPE_CHECKING: + from collections.abc import Mapping + + from deepagents_talon.config import TalonConfig + +logger = logging.getLogger(__name__) + +DEFAULT_API_BASE = "https://api.telegram.org" +DEFAULT_POLL_TIMEOUT_SECONDS = 30.0 +DEFAULT_POLL_INTERVAL_SECONDS = 1.0 +DEFAULT_REQUEST_TIMEOUT_SECONDS = 35.0 +MAX_PHOTO_BYTES = 10 * 1024 * 1024 +MAX_DOCUMENT_BYTES = 50 * 1024 * 1024 +OPEN_EXPOSURE_ACK_ENV = "DEEPAGENTS_TALON_TELEGRAM_OPEN_ACK" +OPEN_EXPOSURE_ACK_VALUE = "allow-arbitrary-senders" +_OFFSET_FILENAME = "telegram_offset.json" + +# MarkdownV2 special characters that must be escaped. +_MARKDOWNV2_SPECIAL = re.compile(r"([_*\[\]()~`>#=+\-|{}.!\\])") + + +class TelegramError(RuntimeError): + """Raised when the Telegram Bot API reports or causes a transport error.""" + + +@dataclass(frozen=True, slots=True) +class TelegramChannelConfig: + """Configuration for the Telegram channel adapter. + + Args: + bot_token: Telegram Bot API authentication token. + session_dir: Directory for Telegram session state (offset file). + inbound_media_dir: Directory where inbound media is downloaded. + outbound_media_dir: Optional root that outbound media must remain under. + api_base: Telegram Bot API base URL. + exposure: Inbound trigger policy. + poll_timeout_seconds: Long-polling timeout passed to getUpdates. + poll_interval_seconds: Delay between getUpdates calls. + request_timeout_seconds: Per-request HTTP timeout for Bot API calls. + operator_id: Telegram user ID for the operator (self exposure mode). + """ + + bot_token: str = field(repr=False) + session_dir: Path + inbound_media_dir: Path | None = None + outbound_media_dir: Path | None = None + api_base: str = DEFAULT_API_BASE + exposure: ChannelExposure = field(default_factory=ChannelExposure) + poll_timeout_seconds: float = DEFAULT_POLL_TIMEOUT_SECONDS + poll_interval_seconds: float = DEFAULT_POLL_INTERVAL_SECONDS + request_timeout_seconds: float = DEFAULT_REQUEST_TIMEOUT_SECONDS + operator_id: str | None = None + + @classmethod + def from_talon_config(cls, config: TalonConfig) -> TelegramChannelConfig: + """Build Telegram channel configuration from Talon environment values. + + Args: + config: Talon process configuration. + + Returns: + Telegram channel configuration. + + Raises: + ValueError: If the bot token is missing or exposure config is invalid. + """ + env = config.env + token = env.get("DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN") or env.get("TELEGRAM_BOT_TOKEN") + if not token: + msg = ( + "Telegram bot token is required " + "(DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN or TELEGRAM_BOT_TOKEN)" + ) + raise ValueError(msg) + session = Path( + env.get("DEEPAGENTS_TALON_TELEGRAM_SESSION_DIR", str(config.channel_dir / "telegram")), + ) + inbound_media_dir = Path( + env.get( + "DEEPAGENTS_TALON_TELEGRAM_MEDIA_DIR", + str(config.inbound_media_dir / "telegram"), + ), + ) + outbound_media_dir = Path( + env.get("DEEPAGENTS_TALON_OUTBOUND_MEDIA_DIR") + or env.get("DEEPAGENTS_TALON_WORKSPACE") + or "/workspace", + ) + exposure = _exposure_from_env(env) + operator_id = env.get("DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID") + return cls( + bot_token=token, + session_dir=session, + inbound_media_dir=inbound_media_dir, + outbound_media_dir=outbound_media_dir, + api_base=env.get("DEEPAGENTS_TALON_TELEGRAM_API_BASE", DEFAULT_API_BASE), + exposure=exposure, + poll_timeout_seconds=_parse_float( + env.get("DEEPAGENTS_TALON_TELEGRAM_POLL_TIMEOUT_SECONDS"), + DEFAULT_POLL_TIMEOUT_SECONDS, + ), + poll_interval_seconds=_parse_float( + env.get("DEEPAGENTS_TALON_TELEGRAM_POLL_INTERVAL_SECONDS"), + DEFAULT_POLL_INTERVAL_SECONDS, + ), + request_timeout_seconds=_parse_float( + env.get("DEEPAGENTS_TALON_TELEGRAM_REQUEST_TIMEOUT_SECONDS"), + DEFAULT_REQUEST_TIMEOUT_SECONDS, + ), + operator_id=operator_id, + ) + + @property + def offset_file(self) -> Path: + """Path to the persisted getUpdates offset file.""" + return self.session_dir / _OFFSET_FILENAME + + +class TelegramTransport: + """Small JSON HTTP client for the Telegram Bot API.""" + + def __init__(self, *, api_base: str, token: str, timeout: float) -> None: + """Initialize the transport. + + Args: + api_base: Telegram Bot API base URL. + token: Bot API authentication token. + timeout: Request timeout in seconds. + """ + self.api_base = api_base.rstrip("/") + self.token = token + self.timeout = timeout + + async def call(self, method: str, **params: object) -> object: + """Call a Bot API method and return the decoded response. + + Args: + method: Bot API method name (e.g. ``getUpdates``). + **params: Request parameters passed as JSON body. + + Returns: + JSON-decoded response body. + + Raises: + TelegramError: If the request fails or the API returns an error. + """ + return await asyncio.to_thread(self._request, method, params) + + def _request(self, method: str, params: dict[str, object]) -> object: + url = f"{self.api_base}/bot{self.token}/{method}" + body = json.dumps(params).encode() + request = urllib.request.Request( # noqa: S310 # URL is constructed from config. + url, + data=body, + method="POST", + headers={"content-type": "application/json"}, + ) + try: + with urllib.request.urlopen( # noqa: S310 # Bot API URL from config. + request, + timeout=self.timeout, + ) as response: + payload = json.loads(response.read().decode()) + except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as error: + msg = f"Telegram Bot API request failed: {method}" + raise TelegramError(msg) from error + if isinstance(payload, dict) and not cast("Mapping[str, object]", payload).get("ok", True): + description = cast("Mapping[str, object]", payload).get("description", "unknown error") + msg = f"Telegram Bot API error in {method}: {description}" + raise TelegramError(msg) + return payload + + +class TelegramChannel: + """Channel adapter for Telegram via the Bot API with long polling.""" + + def __init__( + self, + config: TelegramChannelConfig, + *, + transport: TelegramTransport | None = None, + ) -> None: + """Initialize the Telegram channel without starting it. + + Args: + config: Telegram channel configuration. + transport: Optional test transport implementing the Bot API. + """ + self.config = config + self._transport = transport or TelegramTransport( + api_base=config.api_base, + token=config.bot_token, + timeout=config.request_timeout_seconds, + ) + self._handler: MessageHandler | None = None + self._poll: asyncio.Task[None] | None = None + self._stopped = asyncio.Event() + self._status = ChannelStatus(provider="telegram", connected=False, detail="disconnected") + self._bot_username: str | None = None + self._operator_id = config.operator_id + self._offset = 0 + + def set_message_handler(self, handler: MessageHandler) -> None: + """Register the host callback for inbound messages. + + Args: + handler: Coroutine callback invoked for accepted inbound messages. + """ + self._handler = handler + + async def start(self) -> None: + """Load persisted offset, call getMe, and start the long-polling loop.""" + self.config.session_dir.mkdir(mode=0o700, parents=True, exist_ok=True) + self.config.session_dir.chmod(0o700) + if self.config.inbound_media_dir is not None: + self.config.inbound_media_dir.mkdir(mode=0o700, parents=True, exist_ok=True) + self.config.inbound_media_dir.chmod(0o700) + self._stopped.clear() + self._offset = _load_offset(self.config.offset_file) + await self._identify_bot() + self._poll = asyncio.create_task(self._poll_updates(), name="talon:telegram:poll") + + async def stop(self) -> None: + """Stop the polling task and mark the channel as disconnected.""" + self._stopped.set() + if self._poll is not None: + self._poll.cancel() + await asyncio.gather(self._poll, return_exceptions=True) + self._poll = None + self._status = ChannelStatus(provider="telegram", connected=False, detail="disconnected") + + async def send_message(self, conversation_id: str, text: str) -> None: + """Send chunked text with MarkdownV2 formatting and plain-text fallback. + + Args: + conversation_id: Telegram chat id. + text: Message content to send. + """ + for chunk in chunk_text(text, limit=MAX_TEXT_CHARS): + escaped = _escape_markdown_v2(chunk) + try: + await self._transport.call( + "sendMessage", + chat_id=conversation_id, + text=escaped, + parse_mode="MarkdownV2", + ) + except TelegramError: + await self._transport.call( + "sendMessage", + chat_id=conversation_id, + text=chunk, + ) + + async def send_media(self, conversation_id: str, media: ChannelMedia) -> None: + """Send validated image or document media to a Telegram chat. + + Args: + conversation_id: Telegram chat id. + media: Media payload to send. + + Raises: + ChannelMediaError: If the media is too large or invalid. + """ + checked = validate_media(media, root=self.config.outbound_media_dir) + _check_telegram_size(checked) + caption = _escape_markdown_v2(checked.caption) if checked.caption else None + path = str(checked.path) + if checked.media_type == "image": + params: dict[str, object] = {"chat_id": conversation_id, "photo": path} + if caption: + params["caption"] = caption + params["parse_mode"] = "MarkdownV2" + await self._transport.call("sendPhoto", **params) + else: + params = {"chat_id": conversation_id, "document": path} + if caption: + params["caption"] = caption + params["parse_mode"] = "MarkdownV2" + await self._transport.call("sendDocument", **params) + + async def send_typing(self, conversation_id: str) -> None: + """Send a Telegram typing indicator. + + Args: + conversation_id: Telegram chat id. + """ + try: + await self._transport.call( + "sendChatAction", + chat_id=conversation_id, + action="typing", + ) + except TelegramError: + logger.debug("Could not send Telegram typing indicator", exc_info=True) + + async def edit_message(self, conversation_id: str, message_id: str, text: str) -> None: + """Edit a previously sent Telegram message. + + Args: + conversation_id: Telegram chat id. + message_id: Telegram message id. + text: Replacement message content. + """ + escaped = _escape_markdown_v2(text) + try: + await self._transport.call( + "editMessageText", + chat_id=conversation_id, + message_id=int(message_id), + text=escaped, + parse_mode="MarkdownV2", + ) + except TelegramError: + await self._transport.call( + "editMessageText", + chat_id=conversation_id, + message_id=int(message_id), + text=text, + ) + + async def status(self) -> ChannelStatus: + """Report the most recent Telegram Bot API connection status.""" + return self._status + + async def _identify_bot(self) -> None: + try: + payload = await self._transport.call("getMe") + except TelegramError: + logger.exception("Telegram getMe failed during startup") + self._status = ChannelStatus( + provider="telegram", + connected=False, + detail="getMe failed", + ) + return + result = _extract_result(payload) + username = result.get("username") if isinstance(result, dict) else None + if isinstance(username, str): + self._bot_username = username + logger.info("Telegram bot connected as @%s", username) + self._status = ChannelStatus( + provider="telegram", + connected=True, + detail=f"connected as @{username}" if isinstance(username, str) else "connected", + ) + + async def _poll_updates(self) -> None: + while not self._stopped.is_set(): + try: + payload = await self._transport.call( + "getUpdates", + offset=self._offset, + timeout=int(self.config.poll_timeout_seconds), + allowed_updates='["message"]', + ) + updates = _extract_updates(payload) + if updates: + self._offset = cast("int", updates[-1]["update_id"]) + 1 + _save_offset(self.config.offset_file, self._offset) + self._status = ChannelStatus( + provider="telegram", + connected=True, + detail="polling", + ) + for update in updates: + message = _parse_update(update) + if message is None: + continue + if not self._is_operator(message): + self._operator_id = message.sender_id + if self.config.exposure.allows(message): + await self._dispatch(message) + else: + logger.debug( + "Dropping Telegram message %s from %s due to exposure policy", + message.message_id, + message.conversation_id, + ) + except (TelegramError, urllib.error.URLError, TimeoutError): + logger.exception("Telegram long-polling error; retrying after interval") + self._status = ChannelStatus( + provider="telegram", + connected=False, + detail="polling error", + ) + except asyncio.CancelledError: + raise + await asyncio.sleep(self.config.poll_interval_seconds) + + def _is_operator(self, message: ChannelMessage) -> bool: + """Auto-capture operator ID from first inbound message if not set.""" + if self._operator_id is not None: + return message.sender_id == self._operator_id + if message.sender_id is not None: + self._operator_id = message.sender_id + return True + return False + + async def _dispatch(self, message: ChannelMessage) -> None: + if self._handler is None: + logger.warning("Dropping Telegram message because no handler is registered") + return + await self._handler(message) + + async def _download_inbound_media(self, file_id: str, destination: Path) -> None: + """Download a file from the Telegram Bot API. + + Args: + file_id: Telegram file identifier. + destination: Local path to save the downloaded file. + """ + payload = await self._transport.call("getFile", file_id=file_id) + result = _extract_result(payload) + file_path = result.get("file_path") if isinstance(result, dict) else None + if not isinstance(file_path, str): + msg = "Telegram getFile response missing file_path" + raise TelegramError(msg) + download_url = f"{self.config.api_base}/file/bot{self.config.bot_token}/{file_path}" + await asyncio.to_thread(_download_file, download_url, destination, self.timeout) + + @property + def timeout(self) -> float: + """Request timeout for downloads.""" + return self.config.request_timeout_seconds + + +def _escape_markdown_v2(text: str) -> str: + """Escape MarkdownV2 special characters. + + Args: + text: Plain text to escape. + + Returns: + Text with all MarkdownV2 special characters escaped. + """ + return _MARKDOWNV2_SPECIAL.sub(r"\\\1", text) + + +def _check_telegram_size(media: ChannelMedia) -> None: + """Validate media size against Telegram-specific limits. + + Args: + media: Validated media payload. + + Raises: + ChannelMediaError: If the file exceeds Telegram's size limit. + """ + size = media.path.stat().st_size + if media.media_type == "image" and size > MAX_PHOTO_BYTES: + msg = f"photo media is too large for Telegram: {size} bytes exceeds {MAX_PHOTO_BYTES}" + raise ChannelMediaError(msg) + if media.media_type != "image" and size > MAX_DOCUMENT_BYTES: + msg = f"document media is too large for Telegram: {size} bytes exceeds {MAX_DOCUMENT_BYTES}" + raise ChannelMediaError(msg) + + +def _extract_result(payload: object) -> dict[str, object]: + """Extract the ``result`` field from a Bot API response. + + Args: + payload: Full Bot API response. + + Returns: + The ``result`` object. + + Raises: + TelegramError: If the response is malformed. + """ + if not isinstance(payload, dict): + msg = "Telegram Bot API response must be an object" + raise TelegramError(msg) + values = cast("Mapping[str, object]", payload) + if not values.get("ok", True): + description = values.get("description", "unknown error") + msg = f"Telegram Bot API error: {description}" + raise TelegramError(msg) + result = values.get("result") + if not isinstance(result, dict): + msg = "Telegram Bot API response missing result" + raise TelegramError(msg) + return cast("dict[str, object]", result) + + +def _extract_updates(payload: object) -> list[dict[str, object]]: + """Extract the list of updates from a getUpdates response. + + Args: + payload: Full Bot API response. + + Returns: + List of update objects. + + Raises: + TelegramError: If the response is malformed. + """ + if not isinstance(payload, dict): + msg = "Telegram getUpdates response must be an object" + raise TelegramError(msg) + values = cast("Mapping[str, object]", payload) + if not values.get("ok", True): + description = values.get("description", "unknown error") + msg = f"Telegram getUpdates error: {description}" + raise TelegramError(msg) + result = values.get("result") + if not isinstance(result, list): + msg = "Telegram getUpdates result must be a list" + raise TelegramError(msg) + return [cast("dict[str, object]", item) for item in result if isinstance(item, dict)] + + +def _parse_update(update: Mapping[str, object]) -> ChannelMessage | None: + """Parse a single Telegram update into a ChannelMessage. + + Args: + update: Raw update object from getUpdates. + + Returns: + Parsed channel message, or ``None`` if the update should be skipped. + """ + message = update.get("message") + if not isinstance(message, dict): + return None + msg = cast("Mapping[str, object]", message) + chat = msg.get("chat") + if not isinstance(chat, dict): + return None + chat_values = cast("Mapping[str, object]", chat) + chat_type = chat_values.get("type") + if chat_type != "private": + return None + chat_id = chat_values.get("id") + if not isinstance(chat_id, int): + return None + message_id = msg.get("message_id") + if not isinstance(message_id, int): + return None + sender = msg.get("from") + sender_id: str | None = None + if isinstance(sender, dict): + sender_id_raw = cast("Mapping[str, object]", sender).get("id") + if isinstance(sender_id_raw, int): + sender_id = str(sender_id_raw) + + text = msg.get("text") + if not isinstance(text, str): + text = "" + + metadata: dict[str, object] = { + "provider": "telegram", + "chat_type": "private", + "from_self": sender_id is not None and sender_id == str(chat_id), + } + + media_info = _extract_media_info(msg) + if media_info is not None: + metadata["media_type"] = media_info[0] + metadata["file_id"] = media_info[1] + + return ChannelMessage( + conversation_id=str(chat_id), + text=text, + sender_id=sender_id, + message_id=str(message_id), + metadata=metadata, + ) + + +def _extract_media_info(msg: Mapping[str, object]) -> tuple[str, str] | None: + """Extract media type and file_id from a Telegram message. + + Args: + msg: Telegram message object. + + Returns: + Tuple of (media_type, file_id), or ``None`` if the message has no media. + """ + photo = msg.get("photo") + voice = msg.get("voice") or msg.get("audio") + document = msg.get("document") + if isinstance(photo, list) and photo: + file_id = _largest_photo_file_id(photo) + if file_id is not None: + return "image", file_id + if isinstance(voice, dict): + file_id = cast("Mapping[str, object]", voice).get("file_id") + if isinstance(file_id, str): + return "voice", file_id + if isinstance(document, dict): + file_id = cast("Mapping[str, object]", document).get("file_id") + if isinstance(file_id, str): + return "document", file_id + return None + + +def _largest_photo_file_id(photo_sizes: object) -> str | None: + """Extract the file_id of the largest photo size from a photo array. + + Args: + photo_sizes: List of photo size objects from a Telegram message. + + Returns: + File id of the largest photo, or ``None``. + """ + if not isinstance(photo_sizes, list): + return None + best: dict[str, object] | None = None + for size in photo_sizes: + if not isinstance(size, dict): + continue + current = best + if current is None: + best = cast("dict[str, object]", size) + else: + current_size = current.get("file_size", 0) + new_size = cast("Mapping[str, object]", size).get("file_size", 0) + if ( + isinstance(new_size, int) + and isinstance(current_size, int) + and new_size > current_size + ): + best = cast("dict[str, object]", size) + if best is None: + return None + file_id = best.get("file_id") + return file_id if isinstance(file_id, str) else None + + +def _download_file(url: str, destination: Path, timeout: float) -> None: + """Download a file from a URL to a local path. + + Args: + url: Source URL. + destination: Destination file path. + timeout: Download timeout in seconds. + """ + destination.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + request = urllib.request.Request(url) # noqa: S310 # URL constructed from Bot API config. + with urllib.request.urlopen( # noqa: S310 # download URL from Telegram API. + request, + timeout=timeout, + ) as response: + destination.write_bytes(response.read()) + destination.chmod(0o600) + + +def _exposure_from_env(env: Mapping[str, str]) -> ChannelExposure: + """Build ChannelExposure from Telegram-specific env vars. + + Args: + env: Environment variable mapping. + + Returns: + Exposure policy for the Telegram channel. + + Raises: + ValueError: If the exposure mode is invalid or open mode is not acknowledged. + """ + mode = _exposure_mode(env.get("DEEPAGENTS_TALON_TELEGRAM_EXPOSURE", ExposureMode.SELF.value)) + if mode == ExposureMode.OPEN: + _require_open_acknowledgement(env) + logger.warning( + "Telegram open exposure enabled; arbitrary senders can trigger the agent with " + "operator credentials and local host access", + ) + conversations = _split_csv(env.get("DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_CHATS", "")) + mentions = tuple(_split_csv(env.get("DEEPAGENTS_TALON_TELEGRAM_MENTION_PATTERNS", ""))) + return ChannelExposure( + mode=mode, + operator_id=env.get("DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID"), + conversations=frozenset(conversations), + mention_patterns=mentions, + ) + + +def _exposure_mode(value: str) -> ExposureMode: + try: + return ExposureMode(value) + except ValueError as error: + modes = ", ".join(mode.value for mode in ExposureMode) + msg = f"invalid Telegram exposure mode {value!r}; expected one of: {modes}" + raise ValueError(msg) from error + + +def _require_open_acknowledgement(env: Mapping[str, str]) -> None: + if env.get(OPEN_EXPOSURE_ACK_ENV) == OPEN_EXPOSURE_ACK_VALUE: + return + msg = ( + "Telegram exposure mode 'open' allows arbitrary senders to trigger the agent with " + "operator credentials and local host access; set " + f"{OPEN_EXPOSURE_ACK_ENV}={OPEN_EXPOSURE_ACK_VALUE} to acknowledge this risk" + ) + raise ValueError(msg) + + +def _split_csv(value: str) -> list[str]: + return [item.strip() for item in value.split(",") if item.strip()] + + +def _parse_float(value: str | None, default: float) -> float: + if value is None: + return default + try: + return float(value) + except ValueError as error: + msg = f"expected float value, got {value!r}" + raise ValueError(msg) from error + + +# --- Offset persistence (ticket 23) --- + + +def _load_offset(offset_file: Path) -> int: + """Load the persisted getUpdates offset from disk. + + Args: + offset_file: Path to the offset state file. + + Returns: + Persisted offset value, or ``0`` if the file is missing or corrupt. + """ + if not offset_file.is_file(): + return 0 + try: + data = json.loads(offset_file.read_text(encoding="utf-8")) + except (json.JSONDecodeError, OSError): + logger.warning("Telegram offset file is corrupt or unreadable; starting with offset=0") + return 0 + offset = data.get("offset") if isinstance(data, dict) else None + if not isinstance(offset, int) or offset < 0: + logger.warning("Telegram offset file contains invalid offset; starting with offset=0") + return 0 + return offset + + +def _save_offset(offset_file: Path, offset: int) -> None: + """Atomically persist the getUpdates offset to disk. + + Args: + offset_file: Path to the offset state file. + offset: Current offset value to persist. + """ + offset_file.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + content = json.dumps({"offset": offset}) + tmp = offset_file.with_suffix(".json.tmp") + tmp.write_text(content, encoding="utf-8") + tmp.chmod(0o600) + tmp.replace(offset_file) diff --git a/libs/talon/deepagents_talon/config.py b/libs/talon/deepagents_talon/config.py index 3c6ea0ed8eb..a8b0dfd5f27 100644 --- a/libs/talon/deepagents_talon/config.py +++ b/libs/talon/deepagents_talon/config.py @@ -16,8 +16,8 @@ _ASSISTANT_ID_PATTERN = re.compile(r"[A-Za-z0-9_.-]{1,128}") _ENV_PREFIX = "DEEPAGENTS_TALON_" -_RUNTIME_ENV_PREFIXES = (_ENV_PREFIX, "AGENT_", "LANGSMITH_", "OPENAI_", "SPEECH_") -_RUNTIME_ENV_KEYS = frozenset({"BUILTIN_MCP_URL", "HOST_LANGCHAIN_API_URL"}) +_RUNTIME_ENV_PREFIXES = (_ENV_PREFIX, "AGENT_", "LANGSMITH_", "OPENAI_", "SPEECH_", "TELEGRAM_") +_RUNTIME_ENV_KEYS = frozenset({"BUILTIN_MCP_URL", "HOST_LANGCHAIN_API_URL", "TELEGRAM_BOT_TOKEN"}) class TalonConfigError(ValueError): diff --git a/libs/talon/tests/channels/test_telegram.py b/libs/talon/tests/channels/test_telegram.py new file mode 100644 index 00000000000..007e66f5528 --- /dev/null +++ b/libs/talon/tests/channels/test_telegram.py @@ -0,0 +1,780 @@ +from __future__ import annotations + +import asyncio +import json +import os +from pathlib import Path +from typing import cast + +import pytest + +from deepagents_talon.channels.base import ( + ChannelExposure, + ChannelMediaError, + ExposureMode, +) +from deepagents_talon.channels.telegram import ( + MAX_DOCUMENT_BYTES, + MAX_PHOTO_BYTES, + TelegramChannel, + TelegramChannelConfig, + TelegramError, + TelegramTransport, + _escape_markdown_v2, + _load_offset, + _save_offset, +) +from deepagents_talon.config import TalonConfig +from deepagents_talon.interfaces import ChannelMedia, ChannelMessage + + +class RecordingTransport: + """Fake transport that records calls and returns canned responses.""" + + def __init__( + self, + updates: list[dict[str, object]] | None = None, + ) -> None: + self.updates = list(updates) if updates else [] + self.calls: list[tuple[str, dict[str, object]]] = [] + self._get_me_called = False + + async def call(self, method: str, **params: object) -> object: + self.calls.append((method, dict(params))) + if method == "getMe": + self._get_me_called = True + return {"ok": True, "result": {"id": 123456, "username": "test_bot"}} + if method == "getUpdates": + updates = self.updates + self.updates = [] + return {"ok": True, "result": updates} + if method == "sendChatAction": + return {"ok": True, "result": True} + if method in ("sendMessage", "sendPhoto", "sendDocument", "editMessageText"): + return {"ok": True, "result": {"message_id": 42}} + if method == "getFile": + return {"ok": True, "result": {"file_id": "abc", "file_path": "photos/file.jpg"}} + return {"ok": True, "result": True} + + +class ErrorOnFirstSuccessTransport: + """Transport that raises on the first getUpdates, then returns empty.""" + + def __init__(self) -> None: + self.calls = 0 + + async def call(self, method: str, **params: object) -> object: # noqa: ARG002 # test fake + if method == "getMe": + return {"ok": True, "result": {"id": 123456, "username": "test_bot"}} + if method == "getUpdates": + self.calls += 1 + if self.calls == 1: + msg = "network error" + raise TelegramError(msg) + return {"ok": True, "result": []} + return {"ok": True, "result": True} + + +class MarkdownV2ErrorTransport: + """Transport that fails MarkdownV2 messages, forcing plain-text fallback.""" + + def __init__(self) -> None: + self.calls: list[tuple[str, dict[str, object]]] = [] + + async def call(self, method: str, **params: object) -> object: + self.calls.append((method, dict(params))) + if method == "getMe": + return {"ok": True, "result": {"id": 123456, "username": "test_bot"}} + if method == "getUpdates": + return {"ok": True, "result": []} + if params.get("parse_mode") == "MarkdownV2": + msg = "Bad Request: can't parse entities" + raise TelegramError(msg) + return {"ok": True, "result": {"message_id": 42}} + + +def _make_update( # noqa: PLR0913 # test helper with many optional fields + *, + update_id: int = 1, + chat_id: int = 111, + sender_id: int = 111, + text: str = "hello", + chat_type: str = "private", + message_id: int = 10, + photo: list | None = None, + voice: dict | None = None, + document: dict | None = None, +) -> dict[str, object]: + message: dict[str, object] = { + "message_id": message_id, + "chat": {"id": chat_id, "type": chat_type}, + "from": {"id": sender_id}, + "text": text, + } + if photo is not None: + message["photo"] = photo + if voice is not None: + message["voice"] = voice + if document is not None: + message["document"] = document + return {"update_id": update_id, "message": message} + + +def _make_config( + tmp_path: Path, + *, + exposure: ChannelExposure | None = None, + operator_id: str | None = None, +) -> TelegramChannelConfig: + return TelegramChannelConfig( + bot_token="test-token", # noqa: S106 # inert test token + session_dir=tmp_path / "telegram", + inbound_media_dir=tmp_path / "telegram" / "media", + outbound_media_dir=tmp_path, + exposure=exposure or ChannelExposure(operator_id=operator_id), + poll_interval_seconds=60, + poll_timeout_seconds=1, + operator_id=operator_id, + ) + + +# --- Config tests --- + + +def test_config_from_talon_env_maps_telegram_values(tmp_path: Path) -> None: + config = TalonConfig.from_env( + { + "AGENT_ASSISTANT_ID": "assistant", + "DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN": "secret-token", + "DEEPAGENTS_TALON_TELEGRAM_EXPOSURE": "allowlist", + "DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_CHATS": "123, 456", + "DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID": "999", + "DEEPAGENTS_TALON_TELEGRAM_POLL_TIMEOUT_SECONDS": "45", + "DEEPAGENTS_TALON_TELEGRAM_POLL_INTERVAL_SECONDS": "2", + }, + base_home=tmp_path, + ) + + telegram = TelegramChannelConfig.from_talon_config(config) + + assert telegram.bot_token == "secret-token" # noqa: S105 # inert test token + assert telegram.session_dir == tmp_path / "assistant" / "channels" / "telegram" + assert telegram.inbound_media_dir == tmp_path / "assistant" / "media" / "inbound" / "telegram" + assert telegram.exposure == ChannelExposure( + mode=ExposureMode.ALLOWLIST, + operator_id="999", + conversations=frozenset({"123", "456"}), + ) + assert telegram.poll_timeout_seconds == 45.0 + assert telegram.poll_interval_seconds == 2.0 + + +def test_config_accepts_telegram_bot_token_alias(tmp_path: Path) -> None: + config = TalonConfig.from_env( + { + "AGENT_ASSISTANT_ID": "assistant", + "TELEGRAM_BOT_TOKEN": "alias-token", + }, + base_home=tmp_path, + ) + + telegram = TelegramChannelConfig.from_talon_config(config) + + assert telegram.bot_token == "alias-token" # noqa: S105 # inert test token + + +def test_config_raises_without_bot_token(tmp_path: Path) -> None: + config = TalonConfig.from_env( + {"AGENT_ASSISTANT_ID": "assistant"}, + base_home=tmp_path, + ) + + with pytest.raises(ValueError, match="bot token is required"): + TelegramChannelConfig.from_talon_config(config) + + +def test_config_rejects_open_exposure_without_acknowledgement(tmp_path: Path) -> None: + config = TalonConfig.from_env( + { + "AGENT_ASSISTANT_ID": "assistant", + "DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN": "token", + "DEEPAGENTS_TALON_TELEGRAM_EXPOSURE": "open", + }, + base_home=tmp_path, + ) + + with pytest.raises(ValueError, match="allow-arbitrary-senders"): + TelegramChannelConfig.from_talon_config(config) + + +def test_config_accepts_open_exposure_with_acknowledgement(tmp_path: Path) -> None: + config = TalonConfig.from_env( + { + "AGENT_ASSISTANT_ID": "assistant", + "DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN": "token", + "DEEPAGENTS_TALON_TELEGRAM_EXPOSURE": "open", + "DEEPAGENTS_TALON_TELEGRAM_OPEN_ACK": "allow-arbitrary-senders", + }, + base_home=tmp_path, + ) + + telegram = TelegramChannelConfig.from_talon_config(config) + + assert telegram.exposure.mode == ExposureMode.OPEN + + +# --- MarkdownV2 escaping tests --- + + +def test_escape_markdown_v2_escapes_special_chars() -> None: + assert _escape_markdown_v2("hello *world*") == r"hello \*world\*" + assert _escape_markdown_v2("a_b_c") == r"a\_b\_c" + assert _escape_markdown_v2("list [1]") == r"list \[1\]" + assert _escape_markdown_v2("not! really.") == r"not\! really\." + assert _escape_markdown_v2("plain text") == "plain text" + + +def test_escape_markdown_v2_escapes_backslash() -> None: + assert _escape_markdown_v2(r"path\to") == r"path\\to" + + +# --- Polling and exposure tests --- + + +async def test_channel_polls_and_dispatches_allowed_messages(tmp_path: Path) -> None: + transport = RecordingTransport( + updates=[ + _make_update(update_id=10, chat_id=111, sender_id=111, text="allowed"), + _make_update(update_id=11, chat_id=333, sender_id=222, text="blocked"), + ], + ) + channel = TelegramChannel( + _make_config(tmp_path, operator_id="111"), + transport=cast("TelegramTransport", transport), + ) + received: list[ChannelMessage] = [] + + async def record(message: ChannelMessage) -> None: + received.append(message) + + channel.set_message_handler(record) + + await channel.start() + await asyncio.sleep(0) + await channel.stop() + + assert [msg.text for msg in received] == ["allowed"] + assert received[0].metadata["provider"] == "telegram" + assert received[0].conversation_id == "111" + assert received[0].message_id == "10" + + +async def test_channel_drops_group_messages(tmp_path: Path) -> None: + transport = RecordingTransport( + updates=[ + _make_update(update_id=1, chat_id=111, sender_id=111, chat_type="group"), + _make_update(update_id=2, chat_id=111, sender_id=111, chat_type="supergroup"), + _make_update(update_id=3, chat_id=111, sender_id=111, chat_type="channel"), + ], + ) + channel = TelegramChannel( + _make_config(tmp_path, exposure=ChannelExposure(mode=ExposureMode.OPEN)), + transport=cast("TelegramTransport", transport), + ) + received: list[ChannelMessage] = [] + + async def record(message: ChannelMessage) -> None: + received.append(message) + + channel.set_message_handler(record) + + await channel.start() + await asyncio.sleep(0) + await channel.stop() + + assert received == [] + + +async def test_channel_auto_captures_operator_id(tmp_path: Path) -> None: + transport = RecordingTransport( + updates=[ + _make_update(update_id=1, chat_id=111, sender_id=111, text="first"), + _make_update(update_id=2, chat_id=111, sender_id=222, text="second"), + ], + ) + channel = TelegramChannel( + _make_config(tmp_path, operator_id=None), + transport=cast("TelegramTransport", transport), + ) + received: list[ChannelMessage] = [] + + async def record(message: ChannelMessage) -> None: + received.append(message) + + channel.set_message_handler(record) + + await channel.start() + await asyncio.sleep(0) + await channel.stop() + + # First message auto-captures operator_id=111, so first is allowed. + # Second has sender_id=222, which doesn't match 111, so it's blocked. + assert [msg.text for msg in received] == ["first"] + + +async def test_channel_survives_transient_polling_error(tmp_path: Path) -> None: + transport = ErrorOnFirstSuccessTransport() + config = _make_config(tmp_path, exposure=ChannelExposure(mode=ExposureMode.OPEN)) + config = TelegramChannelConfig( + bot_token="test-token", # noqa: S106 # inert test token + session_dir=tmp_path / "telegram", + inbound_media_dir=tmp_path / "telegram" / "media", + outbound_media_dir=tmp_path, + exposure=ChannelExposure(mode=ExposureMode.OPEN), + poll_interval_seconds=0.01, + poll_timeout_seconds=1, + ) + channel = TelegramChannel( + config, + transport=cast("TelegramTransport", transport), + ) + + await channel.start() + # Allow enough time for error + retry + success. + await asyncio.sleep(0.1) + await channel.stop() + + assert transport.calls >= 2 # first errored, second succeeded + assert (await channel.status()).provider == "telegram" + + +async def test_channel_identifies_bot_on_start(tmp_path: Path) -> None: + transport = RecordingTransport() + channel = TelegramChannel( + _make_config(tmp_path, exposure=ChannelExposure(mode=ExposureMode.OPEN)), + transport=cast("TelegramTransport", transport), + ) + + await channel.start() + await asyncio.sleep(0) + await channel.stop() + + assert channel._bot_username == "test_bot" + + +# --- Outbound text tests --- + + +async def test_send_message_uses_markdown_v2(tmp_path: Path) -> None: + transport = RecordingTransport() + channel = TelegramChannel( + _make_config(tmp_path), + transport=cast("TelegramTransport", transport), + ) + + await channel.send_message("123", "hello *world*") + + assert transport.calls[0][0] == "sendMessage" + params = transport.calls[0][1] + assert params["parse_mode"] == "MarkdownV2" + assert params["text"] == r"hello \*world\*" + assert params["chat_id"] == "123" + + +async def test_send_message_falls_back_to_plain_text(tmp_path: Path) -> None: + transport = MarkdownV2ErrorTransport() + channel = TelegramChannel( + _make_config(tmp_path), + transport=cast("TelegramTransport", transport), + ) + + await channel.send_message("123", "hello *world*") + + # First call uses MarkdownV2, second is plain text fallback. + assert transport.calls[0][1]["parse_mode"] == "MarkdownV2" + assert "parse_mode" not in transport.calls[1][1] + assert transport.calls[1][1]["text"] == "hello *world*" + + +async def test_send_message_chunks_long_text(tmp_path: Path) -> None: + transport = RecordingTransport() + channel = TelegramChannel( + _make_config(tmp_path), + transport=cast("TelegramTransport", transport), + ) + + long_text = "x" * 5000 + await channel.send_message("123", long_text) + + send_calls = [c for c in transport.calls if c[0] == "sendMessage"] + assert len(send_calls) == 2 + assert len(send_calls[0][1]["text"]) <= 4096 + assert len(send_calls[1][1]["text"]) <= 4096 + + +# --- Outbound media tests --- + + +async def test_send_media_sends_photo_for_images(tmp_path: Path) -> None: + transport = RecordingTransport() + image = tmp_path / "image.png" + image.write_bytes(b"image-data") + channel = TelegramChannel( + _make_config(tmp_path), + transport=cast("TelegramTransport", transport), + ) + + await channel.send_media("123", ChannelMedia(path=image, media_type="image", caption="cap")) + + assert transport.calls[0][0] == "sendPhoto" + assert transport.calls[0][1]["chat_id"] == "123" + assert transport.calls[0][1]["photo"] == str(image) + + +async def test_send_media_sends_document_for_videos(tmp_path: Path) -> None: + transport = RecordingTransport() + video = tmp_path / "clip.mp4" + video.write_bytes(b"video-data") + channel = TelegramChannel( + _make_config(tmp_path), + transport=cast("TelegramTransport", transport), + ) + + await channel.send_media("123", ChannelMedia(path=video, media_type="video")) + + assert transport.calls[0][0] == "sendDocument" + assert transport.calls[0][1]["document"] == str(video) + + +def _patch_file_size( + monkeypatch: pytest.MonkeyPatch, + path: Path, + fake_size: int, +) -> None: + """Patch ``os.stat`` so that *path* reports ``fake_size`` bytes. + + All other paths fall through to the real ``os.stat``. + """ + + real_stat = os.stat + + def patched_stat( + p: str | bytes | Path, + *, + follow_symlinks: bool = True, # signature must match os.stat + ) -> os.stat_result: + if Path(p) == path: + result = real_stat(p, follow_symlinks=follow_symlinks) + return os.stat_result( + ( + result.st_mode, + result.st_ino, + result.st_dev, + result.st_nlink, + result.st_uid, + result.st_gid, + fake_size, + result.st_atime, + result.st_mtime, + result.st_ctime, + ), + ) + return real_stat(p, follow_symlinks=follow_symlinks) + + monkeypatch.setattr(os, "stat", patched_stat) + + +async def test_send_media_rejects_oversized_photo( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + image = tmp_path / "big.png" + image.write_bytes(b"x") + channel = TelegramChannel(_make_config(tmp_path)) + + _patch_file_size(monkeypatch, image, MAX_PHOTO_BYTES + 1) + + with pytest.raises(ChannelMediaError, match="too large for Telegram"): + await channel.send_media("123", ChannelMedia(path=image, media_type="image")) + + +async def test_send_media_rejects_oversized_document( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + video = tmp_path / "big.mp4" + video.write_bytes(b"x") + channel = TelegramChannel(_make_config(tmp_path)) + + _patch_file_size(monkeypatch, video, MAX_DOCUMENT_BYTES + 1) + + with pytest.raises(ChannelMediaError, match="too large for Telegram"): + await channel.send_media("123", ChannelMedia(path=video, media_type="video")) + + +# --- Edit message tests --- + + +async def test_edit_message_uses_markdown_v2(tmp_path: Path) -> None: + transport = RecordingTransport() + channel = TelegramChannel( + _make_config(tmp_path), + transport=cast("TelegramTransport", transport), + ) + + await channel.edit_message("123", "42", "updated *text*") + + assert transport.calls[0][0] == "editMessageText" + assert transport.calls[0][1]["parse_mode"] == "MarkdownV2" + assert transport.calls[0][1]["text"] == r"updated \*text\*" + assert transport.calls[0][1]["message_id"] == 42 + + +async def test_edit_message_falls_back_to_plain_text(tmp_path: Path) -> None: + transport = MarkdownV2ErrorTransport() + channel = TelegramChannel( + _make_config(tmp_path), + transport=cast("TelegramTransport", transport), + ) + + await channel.edit_message("123", "42", "updated *text*") + + edit_calls = [c for c in transport.calls if c[0] == "editMessageText"] + assert len(edit_calls) == 2 + assert edit_calls[0][1]["parse_mode"] == "MarkdownV2" + assert "parse_mode" not in edit_calls[1][1] + assert edit_calls[1][1]["text"] == "updated *text*" + + +# --- Typing indicator tests --- + + +async def test_send_typing_calls_send_chat_action(tmp_path: Path) -> None: + transport = RecordingTransport() + channel = TelegramChannel( + _make_config(tmp_path), + transport=cast("TelegramTransport", transport), + ) + + await channel.send_typing("123") + + assert transport.calls[0] == ("sendChatAction", {"chat_id": "123", "action": "typing"}) + + +async def test_send_typing_swallows_errors(tmp_path: Path) -> None: + class FailingTransport: + async def call(self, method: str, **params: object) -> object: # noqa: ARG002 # test fake + msg = "network error" + raise TelegramError(msg) + + channel = TelegramChannel( + _make_config(tmp_path), + transport=cast("TelegramTransport", FailingTransport()), + ) + + # Should not raise. + await channel.send_typing("123") + + +# --- Inbound media parsing tests --- + + +async def test_channel_parses_inbound_photo(tmp_path: Path) -> None: + transport = RecordingTransport( + updates=[ + _make_update( + update_id=1, + chat_id=111, + sender_id=111, + text="", + photo=[ + {"file_id": "small", "file_size": 100}, + {"file_id": "large", "file_size": 500}, + ], + ), + ], + ) + channel = TelegramChannel( + _make_config(tmp_path, operator_id="111"), + transport=cast("TelegramTransport", transport), + ) + received: list[ChannelMessage] = [] + + async def record(message: ChannelMessage) -> None: + received.append(message) + + channel.set_message_handler(record) + + await channel.start() + await asyncio.sleep(0) + await channel.stop() + + assert received[0].metadata["media_type"] == "image" + assert received[0].metadata["file_id"] == "large" + + +async def test_channel_parses_inbound_voice(tmp_path: Path) -> None: + transport = RecordingTransport( + updates=[ + _make_update( + update_id=1, + chat_id=111, + sender_id=111, + text="", + voice={"file_id": "voice123", "duration": 5}, + ), + ], + ) + channel = TelegramChannel( + _make_config(tmp_path, operator_id="111"), + transport=cast("TelegramTransport", transport), + ) + received: list[ChannelMessage] = [] + + async def record(message: ChannelMessage) -> None: + received.append(message) + + channel.set_message_handler(record) + + await channel.start() + await asyncio.sleep(0) + await channel.stop() + + assert received[0].metadata["media_type"] == "voice" + assert received[0].metadata["file_id"] == "voice123" + + +async def test_channel_parses_inbound_document(tmp_path: Path) -> None: + transport = RecordingTransport( + updates=[ + _make_update( + update_id=1, + chat_id=111, + sender_id=111, + text="", + document={"file_id": "doc123", "file_name": "report.pdf"}, + ), + ], + ) + channel = TelegramChannel( + _make_config(tmp_path, operator_id="111"), + transport=cast("TelegramTransport", transport), + ) + received: list[ChannelMessage] = [] + + async def record(message: ChannelMessage) -> None: + received.append(message) + + channel.set_message_handler(record) + + await channel.start() + await asyncio.sleep(0) + await channel.stop() + + assert received[0].metadata["media_type"] == "document" + assert received[0].metadata["file_id"] == "doc123" + + +# --- Status tests --- + + +async def test_status_reports_disconnected_before_start(tmp_path: Path) -> None: + channel = TelegramChannel(_make_config(tmp_path)) + + status = await channel.status() + + assert status.provider == "telegram" + assert status.connected is False + + +async def test_status_reports_connected_after_start(tmp_path: Path) -> None: + transport = RecordingTransport() + channel = TelegramChannel( + _make_config(tmp_path, exposure=ChannelExposure(mode=ExposureMode.OPEN)), + transport=cast("TelegramTransport", transport), + ) + + await channel.start() + await asyncio.sleep(0) + status = await channel.status() + await channel.stop() + + assert status.connected is True + + +# --- Offset persistence tests (ticket 23) --- + + +def test_offset_round_trip(tmp_path: Path) -> None: + offset_file = tmp_path / "telegram_offset.json" + + _save_offset(offset_file, 42) + loaded = _load_offset(offset_file) + + assert loaded == 42 + + +def test_offset_missing_file_returns_zero(tmp_path: Path) -> None: + assert _load_offset(tmp_path / "nonexistent.json") == 0 + + +def test_offset_corrupt_file_returns_zero(tmp_path: Path) -> None: + offset_file = tmp_path / "telegram_offset.json" + offset_file.write_text("not valid json {{{", encoding="utf-8") + + assert _load_offset(offset_file) == 0 + + +def test_offset_invalid_value_returns_zero(tmp_path: Path) -> None: + offset_file = tmp_path / "telegram_offset.json" + offset_file.write_text(json.dumps({"offset": -5}), encoding="utf-8") + + assert _load_offset(offset_file) == 0 + + +def test_offset_atomic_write(tmp_path: Path) -> None: + offset_file = tmp_path / "telegram_offset.json" + + _save_offset(offset_file, 100) + + # The temp file should have been replaced by the real file. + assert offset_file.is_file() + assert not (tmp_path / "telegram_offset.json.tmp").exists() + data = json.loads(offset_file.read_text(encoding="utf-8")) + assert data == {"offset": 100} + + +async def test_channel_persists_offset_after_polling(tmp_path: Path) -> None: + transport = RecordingTransport( + updates=[ + _make_update(update_id=10, chat_id=111, sender_id=111, text="msg1"), + _make_update(update_id=11, chat_id=111, sender_id=111, text="msg2"), + ], + ) + config = _make_config(tmp_path, operator_id="111") + channel = TelegramChannel(config, transport=cast("TelegramTransport", transport)) + + await channel.start() + await asyncio.sleep(0) + await channel.stop() + + offset = _load_offset(config.offset_file) + assert offset == 12 # last update_id (11) + 1 + + +async def test_channel_loads_persisted_offset_on_start(tmp_path: Path) -> None: + config = _make_config(tmp_path, operator_id="111") + _save_offset(config.offset_file, 100) + + transport = RecordingTransport( + updates=[_make_update(update_id=101, chat_id=111, sender_id=111, text="msg1")], + ) + channel = TelegramChannel(config, transport=cast("TelegramTransport", transport)) + + await channel.start() + await asyncio.sleep(0) + await channel.stop() + + # The getUpdates call should have used offset=100. + get_updates_calls = [c for c in transport.calls if c[0] == "getUpdates"] + assert get_updates_calls[0][1]["offset"] == 100 diff --git a/libs/talon/tests/integration_tests/test_telegram_host.py b/libs/talon/tests/integration_tests/test_telegram_host.py new file mode 100644 index 00000000000..8a483ded327 --- /dev/null +++ b/libs/talon/tests/integration_tests/test_telegram_host.py @@ -0,0 +1,198 @@ +from __future__ import annotations + +import asyncio +from typing import TYPE_CHECKING + +from deepagents_talon.__main__ import _channels +from deepagents_talon.channels.telegram import TelegramChannel +from deepagents_talon.channels.whatsapp import WhatsAppChannel +from deepagents_talon.config import TalonConfig +from deepagents_talon.host import TalonHost +from deepagents_talon.interfaces import AgentRequest, AgentResult, ChannelMessage, ChannelStatus + +if TYPE_CHECKING: + from collections.abc import Awaitable, Callable + from pathlib import Path + + +class RecordingChannel: + def __init__(self, provider: str) -> None: + self.provider = provider + self.handler: Callable[[ChannelMessage], Awaitable[None]] | None = None + self.started = False + self.stopped = False + self.status_report = ChannelStatus(provider=provider, connected=True, detail="connected") + + async def start(self) -> None: + self.started = True + + async def stop(self) -> None: + self.stopped = True + + def set_message_handler(self, handler: Callable[[ChannelMessage], Awaitable[None]]) -> None: + self.handler = handler + + async def send_message(self, conversation_id: str, text: str) -> None: + pass + + async def send_media(self, conversation_id: str, media: object) -> None: + pass + + async def edit_message(self, conversation_id: str, message_id: str, text: str) -> None: + pass + + async def status(self) -> ChannelStatus: + return self.status_report + + async def receive(self, text: str, *, conversation_id: str = "chat") -> None: + if self.handler is None: + msg = "channel handler was not registered" + raise AssertionError(msg) + await self.handler(ChannelMessage(conversation_id=conversation_id, text=text)) + + +class EchoAgent: + def __init__(self) -> None: + self.requests: list[AgentRequest] = [] + + async def start(self) -> None: + pass + + async def stop(self) -> None: + pass + + async def invoke(self, request: AgentRequest) -> AgentResult: + self.requests.append(request) + return AgentResult(text=f"reply:{request.text}") + + +def test_channels_factory_returns_both_when_both_enabled(tmp_path: Path) -> None: + config = TalonConfig.from_env( + { + "AGENT_ASSISTANT_ID": "assistant", + "DEEPAGENTS_TALON_WHATSAPP_ENABLED": "1", + "DEEPAGENTS_TALON_TELEGRAM_ENABLED": "1", + "DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN": "test-token", + }, + base_home=tmp_path, + ) + + channels = _channels(config, whatsapp=False, telegram=False) + + assert len(channels) == 2 + assert isinstance(channels[0], WhatsAppChannel) + assert isinstance(channels[1], TelegramChannel) + + +def test_channels_factory_returns_only_telegram(tmp_path: Path) -> None: + config = TalonConfig.from_env( + { + "AGENT_ASSISTANT_ID": "assistant", + "DEEPAGENTS_TALON_TELEGRAM_ENABLED": "1", + "DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN": "test-token", + }, + base_home=tmp_path, + ) + + channels = _channels(config, whatsapp=False, telegram=False) + + assert len(channels) == 1 + assert isinstance(channels[0], TelegramChannel) + + +def test_channels_factory_returns_only_whatsapp(tmp_path: Path) -> None: + config = TalonConfig.from_env( + { + "AGENT_ASSISTANT_ID": "assistant", + "DEEPAGENTS_TALON_WHATSAPP_ENABLED": "1", + }, + base_home=tmp_path, + ) + + channels = _channels(config, whatsapp=False, telegram=False) + + assert len(channels) == 1 + assert isinstance(channels[0], WhatsAppChannel) + + +def test_channels_factory_returns_neither(tmp_path: Path) -> None: + config = TalonConfig.from_env( + {"AGENT_ASSISTANT_ID": "assistant"}, + base_home=tmp_path, + ) + + channels = _channels(config, whatsapp=False, telegram=False) + + assert channels == () + + +def test_channels_factory_accepts_cli_flags(tmp_path: Path) -> None: + config = TalonConfig.from_env( + { + "AGENT_ASSISTANT_ID": "assistant", + "DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN": "test-token", + }, + base_home=tmp_path, + ) + + channels = _channels(config, whatsapp=True, telegram=True) + + assert len(channels) == 2 + + +async def test_simultaneous_channels_coexist_without_interference(tmp_path: Path) -> None: + whatsapp_channel = RecordingChannel("whatsapp") + telegram_channel = RecordingChannel("telegram") + agent = EchoAgent() + config = TalonConfig.from_env( + {"AGENT_ASSISTANT_ID": "assistant"}, + base_home=tmp_path, + ) + host = TalonHost( + config=config, + agent=agent, + channels=[whatsapp_channel, telegram_channel], + ) + + await host.start() + await whatsapp_channel.receive("hello from whatsapp", conversation_id="wa-chat") + await telegram_channel.receive("hello from telegram", conversation_id="tg-chat") + await _drain() + await host.stop() + + assert whatsapp_channel.started + assert whatsapp_channel.stopped + assert telegram_channel.started + assert telegram_channel.stopped + assert len(agent.requests) == 2 + assert agent.requests[0].text == "hello from whatsapp" + assert agent.requests[0].metadata["channel"] == "whatsapp" + assert agent.requests[1].text == "hello from telegram" + assert agent.requests[1].metadata["channel"] == "telegram" + + +async def test_stop_command_cancels_per_channel(tmp_path: Path) -> None: + whatsapp_channel = RecordingChannel("whatsapp") + telegram_channel = RecordingChannel("telegram") + agent = EchoAgent() + config = TalonConfig.from_env( + {"AGENT_ASSISTANT_ID": "assistant"}, + base_home=tmp_path, + ) + host = TalonHost( + config=config, + agent=agent, + channels=[whatsapp_channel, telegram_channel], + ) + + await host.start() + await whatsapp_channel.receive("/stop", conversation_id="wa-chat") + await _drain() + await host.stop() + + assert len(agent.requests) == 0 + + +async def _drain() -> None: + for _ in range(100): + await asyncio.sleep(0) From 3004cf133c9e111342003cc4f5ff39008a977a33 Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sat, 20 Jun 2026 02:23:57 -0700 Subject: [PATCH 02/48] fix(talon): harden Telegram channel media handling --- .../deepagents_talon/channels/telegram.py | 410 +++++++++++++++--- libs/talon/tests/channels/test_telegram.py | 154 ++++++- .../integration_tests/test_telegram_host.py | 3 + 3 files changed, 490 insertions(+), 77 deletions(-) diff --git a/libs/talon/deepagents_talon/channels/telegram.py b/libs/talon/deepagents_talon/channels/telegram.py index bf1002294a7..163f7fc814a 100644 --- a/libs/talon/deepagents_talon/channels/telegram.py +++ b/libs/talon/deepagents_talon/channels/telegram.py @@ -8,11 +8,12 @@ import asyncio import json import logging +import mimetypes import re +import secrets import urllib.error -import urllib.parse import urllib.request -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from pathlib import Path from typing import TYPE_CHECKING, cast @@ -51,6 +52,16 @@ class TelegramError(RuntimeError): """Raised when the Telegram Bot API reports or causes a transport error.""" +@dataclass(frozen=True, slots=True) +class _TelegramMediaInfo: + """Media metadata extracted from an inbound Telegram message.""" + + media_type: str + file_id: str + file_name: str | None = None + mime_type: str | None = None + + @dataclass(frozen=True, slots=True) class TelegramChannelConfig: """Configuration for the Telegram channel adapter. @@ -145,7 +156,7 @@ def offset_file(self) -> Path: class TelegramTransport: - """Small JSON HTTP client for the Telegram Bot API.""" + """Small HTTP client for the Telegram Bot API.""" def __init__(self, *, api_base: str, token: str, timeout: float) -> None: """Initialize the transport. @@ -163,7 +174,7 @@ async def call(self, method: str, **params: object) -> object: """Call a Bot API method and return the decoded response. Args: - method: Bot API method name (e.g. ``getUpdates``). + method: Bot API method name (e.g. `getUpdates`). **params: Request parameters passed as JSON body. Returns: @@ -174,6 +185,30 @@ async def call(self, method: str, **params: object) -> object: """ return await asyncio.to_thread(self._request, method, params) + async def upload( + self, + method: str, + *, + file_field: str, + file_path: Path, + **params: object, + ) -> object: + """Call a Bot API method with one local file as multipart form data. + + Args: + method: Bot API method name (e.g. `sendPhoto`). + file_field: Multipart field name for the file parameter. + file_path: Local file path to upload. + **params: Additional form fields. + + Returns: + JSON-decoded response body. + + Raises: + TelegramError: If the request fails or the API returns an error. + """ + return await asyncio.to_thread(self._upload, method, file_field, file_path, params) + def _request(self, method: str, params: dict[str, object]) -> object: url = f"{self.api_base}/bot{self.token}/{method}" body = json.dumps(params).encode() @@ -183,6 +218,35 @@ def _request(self, method: str, params: dict[str, object]) -> object: method="POST", headers={"content-type": "application/json"}, ) + return self._send_request(method, request) + + def _upload( + self, + method: str, + file_field: str, + file_path: Path, + params: dict[str, object], + ) -> object: + url = f"{self.api_base}/bot{self.token}/{method}" + boundary = f"deepagents-talon-{secrets.token_hex(16)}" + body = _encode_multipart_form( + params, + file_field=file_field, + file_path=file_path, + boundary=boundary, + ) + request = urllib.request.Request( # noqa: S310 # URL is constructed from config. + url, + data=body, + method="POST", + headers={ + "content-type": f"multipart/form-data; boundary={boundary}", + "content-length": str(len(body)), + }, + ) + return self._send_request(method, request) + + def _send_request(self, method: str, request: urllib.request.Request) -> object: try: with urllib.request.urlopen( # noqa: S310 # Bot API URL from config. request, @@ -192,11 +256,7 @@ def _request(self, method: str, params: dict[str, object]) -> object: except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as error: msg = f"Telegram Bot API request failed: {method}" raise TelegramError(msg) from error - if isinstance(payload, dict) and not cast("Mapping[str, object]", payload).get("ok", True): - description = cast("Mapping[str, object]", payload).get("description", "unknown error") - msg = f"Telegram Bot API error in {method}: {description}" - raise TelegramError(msg) - return payload + return _raise_for_api_error(method, payload) class TelegramChannel: @@ -224,8 +284,9 @@ def __init__( self._poll: asyncio.Task[None] | None = None self._stopped = asyncio.Event() self._status = ChannelStatus(provider="telegram", connected=False, detail="disconnected") + self._exposure = _effective_exposure(config.exposure, config.operator_id) + self._bot_id: str | None = None self._bot_username: str | None = None - self._operator_id = config.operator_id self._offset = 0 def set_message_handler(self, handler: MessageHandler) -> None: @@ -293,19 +354,28 @@ async def send_media(self, conversation_id: str, media: ChannelMedia) -> None: checked = validate_media(media, root=self.config.outbound_media_dir) _check_telegram_size(checked) caption = _escape_markdown_v2(checked.caption) if checked.caption else None - path = str(checked.path) if checked.media_type == "image": - params: dict[str, object] = {"chat_id": conversation_id, "photo": path} + params: dict[str, object] = {"chat_id": conversation_id} if caption: params["caption"] = caption params["parse_mode"] = "MarkdownV2" - await self._transport.call("sendPhoto", **params) + await self._transport.upload( + "sendPhoto", + file_field="photo", + file_path=checked.path, + **params, + ) else: - params = {"chat_id": conversation_id, "document": path} + params = {"chat_id": conversation_id} if caption: params["caption"] = caption params["parse_mode"] = "MarkdownV2" - await self._transport.call("sendDocument", **params) + await self._transport.upload( + "sendDocument", + file_field="document", + file_path=checked.path, + **params, + ) async def send_typing(self, conversation_id: str) -> None: """Send a Telegram typing indicator. @@ -363,6 +433,9 @@ async def _identify_bot(self) -> None: ) return result = _extract_result(payload) + bot_id = result.get("id") if isinstance(result, dict) else None + if isinstance(bot_id, int): + self._bot_id = str(bot_id) username = result.get("username") if isinstance(result, dict) else None if isinstance(username, str): self._bot_username = username @@ -380,7 +453,7 @@ async def _poll_updates(self) -> None: "getUpdates", offset=self._offset, timeout=int(self.config.poll_timeout_seconds), - allowed_updates='["message"]', + allowed_updates=["message"], ) updates = _extract_updates(payload) if updates: @@ -395,16 +468,16 @@ async def _poll_updates(self) -> None: message = _parse_update(update) if message is None: continue - if not self._is_operator(message): - self._operator_id = message.sender_id - if self.config.exposure.allows(message): - await self._dispatch(message) - else: + message = _with_from_self(message, self._bot_id) + if not self._exposure.allows(message): logger.debug( "Dropping Telegram message %s from %s due to exposure policy", message.message_id, message.conversation_id, ) + continue + message = await self._prepare_inbound_media(message) + await self._dispatch(message) except (TelegramError, urllib.error.URLError, TimeoutError): logger.exception("Telegram long-polling error; retrying after interval") self._status = ChannelStatus( @@ -416,27 +489,59 @@ async def _poll_updates(self) -> None: raise await asyncio.sleep(self.config.poll_interval_seconds) - def _is_operator(self, message: ChannelMessage) -> bool: - """Auto-capture operator ID from first inbound message if not set.""" - if self._operator_id is not None: - return message.sender_id == self._operator_id - if message.sender_id is not None: - self._operator_id = message.sender_id - return True - return False - async def _dispatch(self, message: ChannelMessage) -> None: if self._handler is None: logger.warning("Dropping Telegram message because no handler is registered") return await self._handler(message) - async def _download_inbound_media(self, file_id: str, destination: Path) -> None: + async def _prepare_inbound_media(self, message: ChannelMessage) -> ChannelMessage: + media_type = message.metadata.get("media_type") + file_id = message.metadata.get("file_id") + if not isinstance(media_type, str) or not isinstance(file_id, str): + return message + if self.config.inbound_media_dir is None: + return message + + destination = await self._download_inbound_media( + file_id, + media_type=media_type, + message_id=message.message_id, + ) + metadata = dict(message.metadata) + path = str(destination) + metadata["has_media"] = True + metadata["media_paths"] = [path] + metadata["media_path"] = path + if media_type == "voice": + metadata["voice_path"] = path + mime_type = _downloaded_mime_type(destination, metadata) + if mime_type is not None: + metadata["media_mime_types"] = [mime_type] + return ChannelMessage( + conversation_id=message.conversation_id, + text=message.text, + sender_id=message.sender_id, + message_id=message.message_id, + metadata=metadata, + ) + + async def _download_inbound_media( + self, + file_id: str, + *, + media_type: str, + message_id: str | None, + ) -> Path: """Download a file from the Telegram Bot API. Args: file_id: Telegram file identifier. - destination: Local path to save the downloaded file. + media_type: Normalized media category. + message_id: Telegram message identifier used to name the file. + + Returns: + Local path to the downloaded file. """ payload = await self._transport.call("getFile", file_id=file_id) result = _extract_result(payload) @@ -444,8 +549,18 @@ async def _download_inbound_media(self, file_id: str, destination: Path) -> None if not isinstance(file_path, str): msg = "Telegram getFile response missing file_path" raise TelegramError(msg) + if self.config.inbound_media_dir is None: + msg = "Telegram inbound media directory is not configured" + raise TelegramError(msg) + suffix = _safe_suffix(file_path, media_type) + destination = self.config.inbound_media_dir / _inbound_media_filename( + message_id=message_id, + file_id=file_id, + suffix=suffix, + ) download_url = f"{self.config.api_base}/file/bot{self.config.bot_token}/{file_path}" await asyncio.to_thread(_download_file, download_url, destination, self.timeout) + return destination @property def timeout(self) -> float: @@ -483,6 +598,147 @@ def _check_telegram_size(media: ChannelMedia) -> None: raise ChannelMediaError(msg) +def _raise_for_api_error(method: str, payload: object) -> object: + if isinstance(payload, dict) and not cast("Mapping[str, object]", payload).get("ok", True): + description = cast("Mapping[str, object]", payload).get("description", "unknown error") + msg = f"Telegram Bot API error in {method}: {description}" + raise TelegramError(msg) + return payload + + +def _encode_multipart_form( + params: Mapping[str, object], + *, + file_field: str, + file_path: Path, + boundary: str, +) -> bytes: + """Encode request parameters and one file as multipart form data. + + Args: + params: Form fields to include before the file field. + file_field: Multipart field name for the file parameter. + file_path: Local file path to upload. + boundary: Multipart boundary string. + + Returns: + Multipart request body. + """ + chunks: list[bytes] = [] + for key, value in params.items(): + if value is None: + continue + chunks.extend( + [ + f"--{boundary}\r\n".encode(), + ( + f'Content-Disposition: form-data; name="{_form_header_value(key)}"\r\n\r\n' + ).encode(), + _form_field_value(value).encode(), + b"\r\n", + ], + ) + + mime_type = mimetypes.guess_type(file_path.name)[0] or "application/octet-stream" + chunks.extend( + [ + f"--{boundary}\r\n".encode(), + ( + "Content-Disposition: form-data; " + f'name="{_form_header_value(file_field)}"; ' + f'filename="{_form_header_value(file_path.name)}"\r\n' + ).encode(), + f"Content-Type: {mime_type}\r\n\r\n".encode(), + file_path.read_bytes(), + b"\r\n", + f"--{boundary}--\r\n".encode(), + ], + ) + return b"".join(chunks) + + +def _form_header_value(value: str) -> str: + return value.replace("\\", "\\\\").replace('"', '\\"').replace("\r", "").replace("\n", "") + + +def _form_field_value(value: object) -> str: + if isinstance(value, bool): + return "true" if value else "false" + if isinstance(value, (dict, list)): + return json.dumps(value) + return str(value) + + +def _effective_exposure( + exposure: ChannelExposure, + operator_id: str | None, +) -> ChannelExposure: + if ( + exposure.mode != ExposureMode.SELF + or exposure.operator_id is not None + or operator_id is None + ): + return exposure + return replace(exposure, operator_id=operator_id) + + +def _with_from_self(message: ChannelMessage, bot_id: str | None) -> ChannelMessage: + if bot_id is None or message.sender_id != bot_id: + return message + metadata = dict(message.metadata) + metadata["from_self"] = True + return ChannelMessage( + conversation_id=message.conversation_id, + text=message.text, + sender_id=message.sender_id, + message_id=message.message_id, + metadata=metadata, + ) + + +def _downloaded_mime_type(path: Path, metadata: dict[str, object]) -> str | None: + raw = metadata.get("mime_type") + if isinstance(raw, str) and "/" in raw: + return raw + raw_many = metadata.get("media_mime_types") + if isinstance(raw_many, list): + for item in raw_many: + if isinstance(item, str) and "/" in item: + return item + guessed, _ = mimetypes.guess_type(path) + return guessed + + +def _safe_suffix(file_path: str, media_type: str) -> str: + suffix = Path(file_path).suffix.lower() + if re.fullmatch(r"\.[a-z0-9]{1,16}", suffix): + return suffix + return _default_suffix(media_type) + + +def _default_suffix(media_type: str) -> str: + if media_type == "image": + return ".jpg" + if media_type == "voice": + return ".ogg" + return ".bin" + + +def _inbound_media_filename( + *, + message_id: str | None, + file_id: str, + suffix: str, +) -> str: + message = _safe_filename_part(message_id or "message") + token = _safe_filename_part(file_id)[-24:] or "file" + return f"{message}_{token}{suffix}" + + +def _safe_filename_part(value: str) -> str: + return re.sub(r"[^A-Za-z0-9_.-]+", "_", value).strip("._") or "file" + + def _extract_result(payload: object) -> dict[str, object]: """Extract the ``result`` field from a Bot API response. @@ -546,6 +802,22 @@ def _parse_update(update: Mapping[str, object]) -> ChannelMessage | None: Returns: Parsed channel message, or ``None`` if the update should be skipped. """ + values = _private_message_values(update) + if values is None: + return None + msg, chat_id, message_id = values + return ChannelMessage( + conversation_id=str(chat_id), + text=_message_text(msg), + sender_id=_sender_id(msg), + message_id=str(message_id), + metadata=_message_metadata(msg), + ) + + +def _private_message_values( + update: Mapping[str, object], +) -> tuple[Mapping[str, object], int, int] | None: message = update.get("message") if not isinstance(message, dict): return None @@ -563,45 +835,55 @@ def _parse_update(update: Mapping[str, object]) -> ChannelMessage | None: message_id = msg.get("message_id") if not isinstance(message_id, int): return None + return msg, chat_id, message_id + + +def _sender_id(msg: Mapping[str, object]) -> str | None: sender = msg.get("from") - sender_id: str | None = None if isinstance(sender, dict): sender_id_raw = cast("Mapping[str, object]", sender).get("id") if isinstance(sender_id_raw, int): - sender_id = str(sender_id_raw) + return str(sender_id_raw) + return None + +def _message_text(msg: Mapping[str, object]) -> str: text = msg.get("text") if not isinstance(text, str): - text = "" + text = msg.get("caption") + if not isinstance(text, str): + return "" + return text + +def _message_metadata(msg: Mapping[str, object]) -> dict[str, object]: metadata: dict[str, object] = { "provider": "telegram", "chat_type": "private", - "from_self": sender_id is not None and sender_id == str(chat_id), + "from_self": False, } media_info = _extract_media_info(msg) if media_info is not None: - metadata["media_type"] = media_info[0] - metadata["file_id"] = media_info[1] + metadata["media_type"] = media_info.media_type + metadata["file_id"] = media_info.file_id + if media_info.file_name is not None: + metadata["file_name"] = media_info.file_name + if media_info.mime_type is not None: + metadata["mime_type"] = media_info.mime_type + metadata["media_mime_types"] = [media_info.mime_type] - return ChannelMessage( - conversation_id=str(chat_id), - text=text, - sender_id=sender_id, - message_id=str(message_id), - metadata=metadata, - ) + return metadata -def _extract_media_info(msg: Mapping[str, object]) -> tuple[str, str] | None: +def _extract_media_info(msg: Mapping[str, object]) -> _TelegramMediaInfo | None: """Extract media type and file_id from a Telegram message. Args: msg: Telegram message object. Returns: - Tuple of (media_type, file_id), or ``None`` if the message has no media. + Media info, or `None` if the message has no media. """ photo = msg.get("photo") voice = msg.get("voice") or msg.get("audio") @@ -609,18 +891,33 @@ def _extract_media_info(msg: Mapping[str, object]) -> tuple[str, str] | None: if isinstance(photo, list) and photo: file_id = _largest_photo_file_id(photo) if file_id is not None: - return "image", file_id + return _TelegramMediaInfo(media_type="image", file_id=file_id) if isinstance(voice, dict): - file_id = cast("Mapping[str, object]", voice).get("file_id") + values = cast("Mapping[str, object]", voice) + file_id = values.get("file_id") if isinstance(file_id, str): - return "voice", file_id + return _TelegramMediaInfo( + media_type="voice", + file_id=file_id, + mime_type=_optional_str(values.get("mime_type")), + ) if isinstance(document, dict): - file_id = cast("Mapping[str, object]", document).get("file_id") + values = cast("Mapping[str, object]", document) + file_id = values.get("file_id") if isinstance(file_id, str): - return "document", file_id + return _TelegramMediaInfo( + media_type="document", + file_id=file_id, + file_name=_optional_str(values.get("file_name")), + mime_type=_optional_str(values.get("mime_type")), + ) return None +def _optional_str(value: object) -> str | None: + return value if isinstance(value, str) and value else None + + def _largest_photo_file_id(photo_sizes: object) -> str | None: """Extract the file_id of the largest photo size from a photo array. @@ -685,6 +982,13 @@ def _exposure_from_env(env: Mapping[str, str]) -> ChannelExposure: ValueError: If the exposure mode is invalid or open mode is not acknowledged. """ mode = _exposure_mode(env.get("DEEPAGENTS_TALON_TELEGRAM_EXPOSURE", ExposureMode.SELF.value)) + operator_id = env.get("DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID") or None + if mode == ExposureMode.SELF and operator_id is None: + msg = ( + "Telegram self exposure requires DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID; " + "set DEEPAGENTS_TALON_TELEGRAM_EXPOSURE=allowlist or open for other modes" + ) + raise ValueError(msg) if mode == ExposureMode.OPEN: _require_open_acknowledgement(env) logger.warning( @@ -695,7 +999,7 @@ def _exposure_from_env(env: Mapping[str, str]) -> ChannelExposure: mentions = tuple(_split_csv(env.get("DEEPAGENTS_TALON_TELEGRAM_MENTION_PATTERNS", ""))) return ChannelExposure( mode=mode, - operator_id=env.get("DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID"), + operator_id=operator_id, conversations=frozenset(conversations), mention_patterns=mentions, ) diff --git a/libs/talon/tests/channels/test_telegram.py b/libs/talon/tests/channels/test_telegram.py index 007e66f5528..c1a81b8ce6c 100644 --- a/libs/talon/tests/channels/test_telegram.py +++ b/libs/talon/tests/channels/test_telegram.py @@ -8,6 +8,7 @@ import pytest +import deepagents_talon.channels.telegram as telegram_module from deepagents_talon.channels.base import ( ChannelExposure, ChannelMediaError, @@ -20,6 +21,7 @@ TelegramChannelConfig, TelegramError, TelegramTransport, + _encode_multipart_form, _escape_markdown_v2, _load_offset, _save_offset, @@ -37,6 +39,7 @@ def __init__( ) -> None: self.updates = list(updates) if updates else [] self.calls: list[tuple[str, dict[str, object]]] = [] + self.uploads: list[tuple[str, str, Path, dict[str, object]]] = [] self._get_me_called = False async def call(self, method: str, **params: object) -> object: @@ -53,9 +56,27 @@ async def call(self, method: str, **params: object) -> object: if method in ("sendMessage", "sendPhoto", "sendDocument", "editMessageText"): return {"ok": True, "result": {"message_id": 42}} if method == "getFile": - return {"ok": True, "result": {"file_id": "abc", "file_path": "photos/file.jpg"}} + file_id = params.get("file_id") + if file_id == "voice123": + file_path = "voice/file.ogg" + elif file_id == "doc123": + file_path = "documents/report.pdf" + else: + file_path = "photos/file.jpg" + return {"ok": True, "result": {"file_id": file_id, "file_path": file_path}} return {"ok": True, "result": True} + async def upload( + self, + method: str, + *, + file_field: str, + file_path: Path, + **params: object, + ) -> object: + self.uploads.append((method, file_field, file_path, dict(params))) + return {"ok": True, "result": {"message_id": 42}} + class ErrorOnFirstSuccessTransport: """Transport that raises on the first getUpdates, then returns empty.""" @@ -138,6 +159,15 @@ def _make_config( ) +def _stub_download(monkeypatch: pytest.MonkeyPatch) -> None: + def download(url: str, destination: Path, timeout: float) -> None: # noqa: ARG001 + destination.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + destination.write_bytes(b"media-bytes") + destination.chmod(0o600) + + monkeypatch.setattr(telegram_module, "_download_file", download) + + # --- Config tests --- @@ -174,6 +204,7 @@ def test_config_accepts_telegram_bot_token_alias(tmp_path: Path) -> None: { "AGENT_ASSISTANT_ID": "assistant", "TELEGRAM_BOT_TOKEN": "alias-token", + "DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID": "999", }, base_home=tmp_path, ) @@ -183,6 +214,19 @@ def test_config_accepts_telegram_bot_token_alias(tmp_path: Path) -> None: assert telegram.bot_token == "alias-token" # noqa: S105 # inert test token +def test_config_requires_operator_for_self_exposure(tmp_path: Path) -> None: + config = TalonConfig.from_env( + { + "AGENT_ASSISTANT_ID": "assistant", + "DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN": "token", + }, + base_home=tmp_path, + ) + + with pytest.raises(ValueError, match="TELEGRAM_OPERATOR_ID"): + TelegramChannelConfig.from_talon_config(config) + + def test_config_raises_without_bot_token(tmp_path: Path) -> None: config = TalonConfig.from_env( {"AGENT_ASSISTANT_ID": "assistant"}, @@ -295,15 +339,15 @@ async def record(message: ChannelMessage) -> None: assert received == [] -async def test_channel_auto_captures_operator_id(tmp_path: Path) -> None: +async def test_channel_does_not_trust_private_chat_sender_as_self(tmp_path: Path) -> None: transport = RecordingTransport( updates=[ - _make_update(update_id=1, chat_id=111, sender_id=111, text="first"), - _make_update(update_id=2, chat_id=111, sender_id=222, text="second"), + _make_update(update_id=1, chat_id=111, sender_id=111, text="attacker"), + _make_update(update_id=2, chat_id=999, sender_id=999, text="operator"), ], ) channel = TelegramChannel( - _make_config(tmp_path, operator_id=None), + _make_config(tmp_path, operator_id="999"), transport=cast("TelegramTransport", transport), ) received: list[ChannelMessage] = [] @@ -314,12 +358,11 @@ async def record(message: ChannelMessage) -> None: channel.set_message_handler(record) await channel.start() - await asyncio.sleep(0) + await _wait_for_received(received, 1) await channel.stop() - # First message auto-captures operator_id=111, so first is allowed. - # Second has sender_id=222, which doesn't match 111, so it's blocked. - assert [msg.text for msg in received] == ["first"] + assert [msg.text for msg in received] == ["operator"] + assert received[0].metadata["from_self"] is False async def test_channel_survives_transient_polling_error(tmp_path: Path) -> None: @@ -408,8 +451,8 @@ async def test_send_message_chunks_long_text(tmp_path: Path) -> None: send_calls = [c for c in transport.calls if c[0] == "sendMessage"] assert len(send_calls) == 2 - assert len(send_calls[0][1]["text"]) <= 4096 - assert len(send_calls[1][1]["text"]) <= 4096 + assert len(cast("str", send_calls[0][1]["text"])) <= 4096 + assert len(cast("str", send_calls[1][1]["text"])) <= 4096 # --- Outbound media tests --- @@ -426,9 +469,14 @@ async def test_send_media_sends_photo_for_images(tmp_path: Path) -> None: await channel.send_media("123", ChannelMedia(path=image, media_type="image", caption="cap")) - assert transport.calls[0][0] == "sendPhoto" - assert transport.calls[0][1]["chat_id"] == "123" - assert transport.calls[0][1]["photo"] == str(image) + assert transport.uploads == [ + ( + "sendPhoto", + "photo", + image, + {"chat_id": "123", "caption": "cap", "parse_mode": "MarkdownV2"}, + ), + ] async def test_send_media_sends_document_for_videos(tmp_path: Path) -> None: @@ -442,8 +490,25 @@ async def test_send_media_sends_document_for_videos(tmp_path: Path) -> None: await channel.send_media("123", ChannelMedia(path=video, media_type="video")) - assert transport.calls[0][0] == "sendDocument" - assert transport.calls[0][1]["document"] == str(video) + assert transport.uploads == [("sendDocument", "document", video, {"chat_id": "123"})] + + +def test_multipart_form_encodes_local_file_upload(tmp_path: Path) -> None: + image = tmp_path / "image.png" + image.write_bytes(b"image-data") + + body = _encode_multipart_form( + {"chat_id": "123", "caption": "hello"}, + file_field="photo", + file_path=image, + boundary="test-boundary", + ) + + assert b'name="chat_id"\r\n\r\n123' in body + assert b'name="caption"\r\n\r\nhello' in body + assert b'name="photo"; filename="image.png"' in body + assert b"Content-Type: image/png" in body + assert b"image-data" in body def _patch_file_size( @@ -463,7 +528,7 @@ def patched_stat( *, follow_symlinks: bool = True, # signature must match os.stat ) -> os.stat_result: - if Path(p) == path: + if Path(os.fsdecode(p)) == path: result = real_stat(p, follow_symlinks=follow_symlinks) return os.stat_result( ( @@ -579,7 +644,11 @@ async def call(self, method: str, **params: object) -> object: # noqa: ARG002 # --- Inbound media parsing tests --- -async def test_channel_parses_inbound_photo(tmp_path: Path) -> None: +async def test_channel_parses_inbound_photo( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + _stub_download(monkeypatch) transport = RecordingTransport( updates=[ _make_update( @@ -606,14 +675,26 @@ async def record(message: ChannelMessage) -> None: channel.set_message_handler(record) await channel.start() - await asyncio.sleep(0) + await _wait_for_received(received, 1) await channel.stop() assert received[0].metadata["media_type"] == "image" assert received[0].metadata["file_id"] == "large" + assert received[0].metadata["media_paths"] == [ + str(tmp_path / "telegram" / "media" / "10_large.jpg"), + ] + assert received[0].metadata["media_path"] == str( + tmp_path / "telegram" / "media" / "10_large.jpg", + ) + media_path = Path(cast("str", received[0].metadata["media_path"])) + assert await asyncio.to_thread(media_path.read_bytes) == b"media-bytes" -async def test_channel_parses_inbound_voice(tmp_path: Path) -> None: +async def test_channel_parses_inbound_voice( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + _stub_download(monkeypatch) transport = RecordingTransport( updates=[ _make_update( @@ -637,14 +718,21 @@ async def record(message: ChannelMessage) -> None: channel.set_message_handler(record) await channel.start() - await asyncio.sleep(0) + await _wait_for_received(received, 1) await channel.stop() assert received[0].metadata["media_type"] == "voice" assert received[0].metadata["file_id"] == "voice123" + assert received[0].metadata["voice_path"] == str( + tmp_path / "telegram" / "media" / "10_voice123.ogg", + ) -async def test_channel_parses_inbound_document(tmp_path: Path) -> None: +async def test_channel_parses_inbound_document( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + _stub_download(monkeypatch) transport = RecordingTransport( updates=[ _make_update( @@ -652,7 +740,11 @@ async def test_channel_parses_inbound_document(tmp_path: Path) -> None: chat_id=111, sender_id=111, text="", - document={"file_id": "doc123", "file_name": "report.pdf"}, + document={ + "file_id": "doc123", + "file_name": "report.pdf", + "mime_type": "application/pdf", + }, ), ], ) @@ -668,11 +760,16 @@ async def record(message: ChannelMessage) -> None: channel.set_message_handler(record) await channel.start() - await asyncio.sleep(0) + await _wait_for_received(received, 1) await channel.stop() assert received[0].metadata["media_type"] == "document" assert received[0].metadata["file_id"] == "doc123" + assert received[0].metadata["file_name"] == "report.pdf" + assert received[0].metadata["media_mime_types"] == ["application/pdf"] + assert received[0].metadata["media_paths"] == [ + str(tmp_path / "telegram" / "media" / "10_doc123.pdf"), + ] # --- Status tests --- @@ -778,3 +875,12 @@ async def test_channel_loads_persisted_offset_on_start(tmp_path: Path) -> None: # The getUpdates call should have used offset=100. get_updates_calls = [c for c in transport.calls if c[0] == "getUpdates"] assert get_updates_calls[0][1]["offset"] == 100 + + +async def _wait_for_received(messages: list[ChannelMessage], count: int) -> None: + for _ in range(100): + if len(messages) >= count: + return + await asyncio.sleep(0) + msg = f"received {len(messages)} message(s), expected {count}" + raise AssertionError(msg) diff --git a/libs/talon/tests/integration_tests/test_telegram_host.py b/libs/talon/tests/integration_tests/test_telegram_host.py index 8a483ded327..211b79b0d76 100644 --- a/libs/talon/tests/integration_tests/test_telegram_host.py +++ b/libs/talon/tests/integration_tests/test_telegram_host.py @@ -73,6 +73,7 @@ def test_channels_factory_returns_both_when_both_enabled(tmp_path: Path) -> None "DEEPAGENTS_TALON_WHATSAPP_ENABLED": "1", "DEEPAGENTS_TALON_TELEGRAM_ENABLED": "1", "DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN": "test-token", + "DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID": "999", }, base_home=tmp_path, ) @@ -90,6 +91,7 @@ def test_channels_factory_returns_only_telegram(tmp_path: Path) -> None: "AGENT_ASSISTANT_ID": "assistant", "DEEPAGENTS_TALON_TELEGRAM_ENABLED": "1", "DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN": "test-token", + "DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID": "999", }, base_home=tmp_path, ) @@ -131,6 +133,7 @@ def test_channels_factory_accepts_cli_flags(tmp_path: Path) -> None: { "AGENT_ASSISTANT_ID": "assistant", "DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN": "test-token", + "DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID": "999", }, base_home=tmp_path, ) From acd9feddd99b7b8de3f9f39a26b2cf93ac4d21b3 Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sat, 20 Jun 2026 10:08:19 -0700 Subject: [PATCH 03/48] fix(talon): process Telegram channel posts and allowlisted users --- libs/talon/README.md | 17 +++ .../deepagents_talon/channels/telegram.py | 51 ++++++-- libs/talon/tests/channels/test_telegram.py | 112 ++++++++++++++++++ 3 files changed, 169 insertions(+), 11 deletions(-) diff --git a/libs/talon/README.md b/libs/talon/README.md index 8fd36b0d270..04db1aafafc 100644 --- a/libs/talon/README.md +++ b/libs/talon/README.md @@ -82,6 +82,23 @@ DEEPAGENTS_TALON_WHATSAPP_OPEN_ACK=allow-arbitrary-senders See `../../examples/talon-whatsapp/` for a runnable Docker Compose topology and `.env` reference. +## Telegram + +The Telegram channel uses the Bot API with long polling. Provide a bot token from BotFather and either a model or Fleet export so Talon runs the real Deep Agents runtime instead of the echo runtime: + +```bash +DEEPAGENTS_TALON_TELEGRAM_ENABLED=true \ +DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN=... \ +DEEPAGENTS_TALON_TELEGRAM_EXPOSURE=allowlist \ +DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_USERS=123456789 \ +DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_CHATS=-1001234567890 \ +AGENT_ASSISTANT_ID=telegram-local \ +AGENT_MODEL=openai:gpt-5.2 \ +uv run deepagents-talon --telegram +``` + +In `allowlist` mode, `DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_USERS` allows private bot DMs from specific Telegram user IDs, while `DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_CHATS` allows channel posts from specific channel chat IDs. If `AGENT_MODEL`, `DEEPAGENTS_TALON_MODEL`, and `DEEPAGENTS_TALON_FLEET_DIR` are all unset, Talon uses the echo runtime and replies with the inbound text unchanged. + ## Tracing LangSmith tracing is opt-in. Set both values before starting the host: diff --git a/libs/talon/deepagents_talon/channels/telegram.py b/libs/talon/deepagents_talon/channels/telegram.py index 163f7fc814a..a9795316f41 100644 --- a/libs/talon/deepagents_talon/channels/telegram.py +++ b/libs/talon/deepagents_talon/channels/telegram.py @@ -43,6 +43,7 @@ OPEN_EXPOSURE_ACK_ENV = "DEEPAGENTS_TALON_TELEGRAM_OPEN_ACK" OPEN_EXPOSURE_ACK_VALUE = "allow-arbitrary-senders" _OFFSET_FILENAME = "telegram_offset.json" +_ALLOWED_UPDATES = ["message", "channel_post"] # MarkdownV2 special characters that must be escaped. _MARKDOWNV2_SPECIAL = re.compile(r"([_*\[\]()~`>#=+\-|{}.!\\])") @@ -77,6 +78,8 @@ class TelegramChannelConfig: poll_interval_seconds: Delay between getUpdates calls. request_timeout_seconds: Per-request HTTP timeout for Bot API calls. operator_id: Telegram user ID for the operator (self exposure mode). + allowed_user_ids: Telegram user IDs allowed to trigger private chats in + allowlist exposure mode. """ bot_token: str = field(repr=False) @@ -89,6 +92,7 @@ class TelegramChannelConfig: poll_interval_seconds: float = DEFAULT_POLL_INTERVAL_SECONDS request_timeout_seconds: float = DEFAULT_REQUEST_TIMEOUT_SECONDS operator_id: str | None = None + allowed_user_ids: frozenset[str] = field(default_factory=frozenset) @classmethod def from_talon_config(cls, config: TalonConfig) -> TelegramChannelConfig: @@ -147,6 +151,9 @@ def from_talon_config(cls, config: TalonConfig) -> TelegramChannelConfig: DEFAULT_REQUEST_TIMEOUT_SECONDS, ), operator_id=operator_id, + allowed_user_ids=frozenset( + _split_csv(env.get("DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_USERS", "")), + ), ) @property @@ -453,7 +460,7 @@ async def _poll_updates(self) -> None: "getUpdates", offset=self._offset, timeout=int(self.config.poll_timeout_seconds), - allowed_updates=["message"], + allowed_updates=_ALLOWED_UPDATES, ) updates = _extract_updates(payload) if updates: @@ -469,7 +476,11 @@ async def _poll_updates(self) -> None: if message is None: continue message = _with_from_self(message, self._bot_id) - if not self._exposure.allows(message): + if not _allows_telegram_message( + self._exposure, + self.config.allowed_user_ids, + message, + ): logger.debug( "Dropping Telegram message %s from %s due to exposure policy", message.message_id, @@ -696,6 +707,20 @@ def _with_from_self(message: ChannelMessage, bot_id: str | None) -> ChannelMessa ) +def _allows_telegram_message( + exposure: ChannelExposure, + allowed_user_ids: frozenset[str], + message: ChannelMessage, +) -> bool: + if ( + exposure.mode == ExposureMode.ALLOWLIST + and message.metadata.get("chat_type") == "private" + and message.sender_id in allowed_user_ids + ): + return True + return exposure.allows(message) + + def _downloaded_mime_type(path: Path, metadata: dict[str, object]) -> str | None: raw = metadata.get("mime_type") if isinstance(raw, str) and "/" in raw: @@ -802,23 +827,27 @@ def _parse_update(update: Mapping[str, object]) -> ChannelMessage | None: Returns: Parsed channel message, or ``None`` if the update should be skipped. """ - values = _private_message_values(update) + values = _message_values(update) if values is None: return None - msg, chat_id, message_id = values + msg, chat_id, message_id, chat_type = values return ChannelMessage( conversation_id=str(chat_id), text=_message_text(msg), sender_id=_sender_id(msg), message_id=str(message_id), - metadata=_message_metadata(msg), + metadata=_message_metadata(msg, chat_type=chat_type), ) -def _private_message_values( +def _message_values( update: Mapping[str, object], -) -> tuple[Mapping[str, object], int, int] | None: +) -> tuple[Mapping[str, object], int, int, str] | None: message = update.get("message") + expected_chat_type = "private" + if not isinstance(message, dict): + message = update.get("channel_post") + expected_chat_type = "channel" if not isinstance(message, dict): return None msg = cast("Mapping[str, object]", message) @@ -827,7 +856,7 @@ def _private_message_values( return None chat_values = cast("Mapping[str, object]", chat) chat_type = chat_values.get("type") - if chat_type != "private": + if chat_type != expected_chat_type: return None chat_id = chat_values.get("id") if not isinstance(chat_id, int): @@ -835,7 +864,7 @@ def _private_message_values( message_id = msg.get("message_id") if not isinstance(message_id, int): return None - return msg, chat_id, message_id + return msg, chat_id, message_id, expected_chat_type def _sender_id(msg: Mapping[str, object]) -> str | None: @@ -856,10 +885,10 @@ def _message_text(msg: Mapping[str, object]) -> str: return text -def _message_metadata(msg: Mapping[str, object]) -> dict[str, object]: +def _message_metadata(msg: Mapping[str, object], *, chat_type: str) -> dict[str, object]: metadata: dict[str, object] = { "provider": "telegram", - "chat_type": "private", + "chat_type": chat_type, "from_self": False, } diff --git a/libs/talon/tests/channels/test_telegram.py b/libs/talon/tests/channels/test_telegram.py index c1a81b8ce6c..4089f7e2526 100644 --- a/libs/talon/tests/channels/test_telegram.py +++ b/libs/talon/tests/channels/test_telegram.py @@ -141,11 +141,29 @@ def _make_update( # noqa: PLR0913 # test helper with many optional fields return {"update_id": update_id, "message": message} +def _make_channel_post( + *, + update_id: int = 1, + chat_id: int = -100111, + text: str = "channel input", + message_id: int = 10, +) -> dict[str, object]: + return { + "update_id": update_id, + "channel_post": { + "message_id": message_id, + "chat": {"id": chat_id, "type": "channel"}, + "text": text, + }, + } + + def _make_config( tmp_path: Path, *, exposure: ChannelExposure | None = None, operator_id: str | None = None, + allowed_user_ids: frozenset[str] | None = None, ) -> TelegramChannelConfig: return TelegramChannelConfig( bot_token="test-token", # noqa: S106 # inert test token @@ -156,6 +174,7 @@ def _make_config( poll_interval_seconds=60, poll_timeout_seconds=1, operator_id=operator_id, + allowed_user_ids=allowed_user_ids or frozenset(), ) @@ -178,6 +197,7 @@ def test_config_from_talon_env_maps_telegram_values(tmp_path: Path) -> None: "DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN": "secret-token", "DEEPAGENTS_TALON_TELEGRAM_EXPOSURE": "allowlist", "DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_CHATS": "123, 456", + "DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_USERS": "777, 888", "DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID": "999", "DEEPAGENTS_TALON_TELEGRAM_POLL_TIMEOUT_SECONDS": "45", "DEEPAGENTS_TALON_TELEGRAM_POLL_INTERVAL_SECONDS": "2", @@ -195,6 +215,7 @@ def test_config_from_talon_env_maps_telegram_values(tmp_path: Path) -> None: operator_id="999", conversations=frozenset({"123", "456"}), ) + assert telegram.allowed_user_ids == frozenset({"777", "888"}) assert telegram.poll_timeout_seconds == 45.0 assert telegram.poll_interval_seconds == 2.0 @@ -311,6 +332,97 @@ async def record(message: ChannelMessage) -> None: assert received[0].metadata["provider"] == "telegram" assert received[0].conversation_id == "111" assert received[0].message_id == "10" + get_updates_calls = [call for call in transport.calls if call[0] == "getUpdates"] + assert get_updates_calls[0][1]["allowed_updates"] == ["message", "channel_post"] + + +async def test_channel_polls_and_dispatches_allowed_channel_posts(tmp_path: Path) -> None: + transport = RecordingTransport( + updates=[_make_channel_post(update_id=10, chat_id=-100111, text="from channel")], + ) + channel = TelegramChannel( + _make_config( + tmp_path, + exposure=ChannelExposure( + mode=ExposureMode.ALLOWLIST, + conversations=frozenset({"-100111"}), + ), + ), + transport=cast("TelegramTransport", transport), + ) + received: list[ChannelMessage] = [] + + async def record(message: ChannelMessage) -> None: + received.append(message) + + channel.set_message_handler(record) + + await channel.start() + await _wait_for_received(received, 1) + await channel.stop() + + assert received[0].text == "from channel" + assert received[0].conversation_id == "-100111" + assert received[0].sender_id is None + assert received[0].message_id == "10" + assert received[0].metadata["chat_type"] == "channel" + + +async def test_channel_polls_and_dispatches_allowed_private_users(tmp_path: Path) -> None: + transport = RecordingTransport( + updates=[ + _make_update(update_id=10, chat_id=111, sender_id=111, text="allowed user"), + _make_update(update_id=11, chat_id=222, sender_id=222, text="blocked user"), + ], + ) + channel = TelegramChannel( + _make_config( + tmp_path, + exposure=ChannelExposure( + mode=ExposureMode.ALLOWLIST, + conversations=frozenset({"-100111"}), + ), + allowed_user_ids=frozenset({"111"}), + ), + transport=cast("TelegramTransport", transport), + ) + received: list[ChannelMessage] = [] + + async def record(message: ChannelMessage) -> None: + received.append(message) + + channel.set_message_handler(record) + + await channel.start() + await asyncio.sleep(0) + await channel.stop() + + assert [msg.text for msg in received] == ["allowed user"] + assert received[0].conversation_id == "111" + assert received[0].sender_id == "111" + assert received[0].metadata["chat_type"] == "private" + + +async def test_channel_posts_do_not_pass_self_exposure(tmp_path: Path) -> None: + transport = RecordingTransport( + updates=[_make_channel_post(update_id=10, chat_id=-100111, text="from channel")], + ) + channel = TelegramChannel( + _make_config(tmp_path, operator_id="111"), + transport=cast("TelegramTransport", transport), + ) + received: list[ChannelMessage] = [] + + async def record(message: ChannelMessage) -> None: + received.append(message) + + channel.set_message_handler(record) + + await channel.start() + await asyncio.sleep(0) + await channel.stop() + + assert received == [] async def test_channel_drops_group_messages(tmp_path: Path) -> None: From e346227284cf4627b86ac58b22dd0c62f93915ea Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sat, 20 Jun 2026 10:16:12 -0700 Subject: [PATCH 04/48] docs(talon): rename Docker example for Telegram --- examples/talon-docker/.env.example | 34 ++++ .../AGENTS.md | 0 .../Dockerfile | 4 +- examples/talon-docker/README.md | 155 ++++++++++++++++++ .../docker-compose.yml | 12 +- examples/talon-whatsapp/.env.example | 25 --- examples/talon-whatsapp/README.md | 62 ------- libs/talon/README.md | 10 +- 8 files changed, 203 insertions(+), 99 deletions(-) create mode 100644 examples/talon-docker/.env.example rename examples/{talon-whatsapp => talon-docker}/AGENTS.md (100%) rename examples/{talon-whatsapp => talon-docker}/Dockerfile (94%) create mode 100644 examples/talon-docker/README.md rename examples/{talon-whatsapp => talon-docker}/docker-compose.yml (57%) delete mode 100644 examples/talon-whatsapp/.env.example delete mode 100644 examples/talon-whatsapp/README.md diff --git a/examples/talon-docker/.env.example b/examples/talon-docker/.env.example new file mode 100644 index 00000000000..103b51df1be --- /dev/null +++ b/examples/talon-docker/.env.example @@ -0,0 +1,34 @@ +# Runtime +AGENT_ASSISTANT_ID=talon-docker-local +AGENT_MODEL= + +# Provider credentials. Keep real values only in your local `.env`. +OPENAI_API_KEY= +ANTHROPIC_API_KEY= + +# WhatsApp is enabled by default for this example. +# Scan the QR code with your phone to bridge WhatsApp to Talon. Set allowlists and mention patterns to control exposure. +DEEPAGENTS_TALON_WHATSAPP_ENABLED=true +DEEPAGENTS_TALON_WHATSAPP_START_BRIDGE=true +DEEPAGENTS_TALON_WHATSAPP_EXPOSURE=self +DEEPAGENTS_TALON_WHATSAPP_ALLOWLIST_CHATS= +DEEPAGENTS_TALON_WHATSAPP_MENTION_PATTERNS= + +# Telegram is disabled by default. Set the bot token and allowlists before enabling. +# Ask @botfather for a bot token to enable Telegram integration. +# Ask @userinfobbot for user and chat IDs to populate the allowlists. +DEEPAGENTS_TALON_TELEGRAM_ENABLED=false +DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN= +DEEPAGENTS_TALON_TELEGRAM_EXPOSURE=allowlist +DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_USERS= +DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_CHATS= +DEEPAGENTS_TALON_TELEGRAM_MENTION_PATTERNS= + +# Voice transcription applies to inbound channel media. +DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_ENABLED=true +DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_DEVICE=cpu + +# Optional tracing. +LANGSMITH_TRACING=false +LANGSMITH_API_KEY= +LANGSMITH_PROJECT=deepagents-talon diff --git a/examples/talon-whatsapp/AGENTS.md b/examples/talon-docker/AGENTS.md similarity index 100% rename from examples/talon-whatsapp/AGENTS.md rename to examples/talon-docker/AGENTS.md diff --git a/examples/talon-whatsapp/Dockerfile b/examples/talon-docker/Dockerfile similarity index 94% rename from examples/talon-whatsapp/Dockerfile rename to examples/talon-docker/Dockerfile index a167a2708ab..e24b61b2f3b 100644 --- a/examples/talon-whatsapp/Dockerfile +++ b/examples/talon-docker/Dockerfile @@ -48,7 +48,7 @@ WORKDIR /opt/deepagents-src COPY libs/deepagents ./libs/deepagents COPY libs/code ./libs/code COPY libs/talon ./libs/talon -COPY examples/talon-whatsapp/AGENTS.md /opt/deepagents-talon/AGENTS.md +COPY examples/talon-docker/AGENTS.md /opt/deepagents-talon/AGENTS.md RUN mkdir -p /opt/whatsapp-bridge && \ cp libs/talon/deepagents_talon/channels/whatsapp_bridge/package.json \ @@ -60,4 +60,4 @@ RUN cd libs/talon && uv sync --frozen --extra speech WORKDIR /workspace -CMD ["/opt/deepagents-talon-venv/bin/deepagents-talon", "--whatsapp"] +CMD ["/opt/deepagents-talon-venv/bin/deepagents-talon"] diff --git a/examples/talon-docker/README.md b/examples/talon-docker/README.md new file mode 100644 index 00000000000..38f6b0228bd --- /dev/null +++ b/examples/talon-docker/README.md @@ -0,0 +1,155 @@ +# Talon Docker Example + +This example runs one Deep Agents Talon host in Docker. It can run WhatsApp, +Telegram, or both channels against the same local assistant state and workspace. + +> **Experimental:** Talon is an experimental runtime and is subject to change or +> removal at any time. + +The host `~/agent-workspace/` directory is mounted at `/workspace`. Cron records, +downloaded inbound media, channel session state, and agent-created files persist +under that host directory. + +## Run + +```bash +cp .env.example .env +mkdir -p ~/agent-workspace + +# Fill AGENT_MODEL and the required provider credentials in .env. +# Enable the channels you want, then build once and run: +docker compose build +docker compose up +``` + +The image installs the Talon package at build time. Rebuild after changing the +Dockerfile, system packages, Node dependencies, or Talon Python dependencies. + +## Channel Setup + +### WhatsApp + +The sample `.env.example` enables WhatsApp by default: + +```bash +DEEPAGENTS_TALON_WHATSAPP_ENABLED=true +DEEPAGENTS_TALON_WHATSAPP_START_BRIDGE=true +DEEPAGENTS_TALON_WHATSAPP_EXPOSURE=self +``` + +On first run, scan the QR code printed by the bridge. With `self` exposure, only +messages from the paired WhatsApp account trigger the agent. Use `allowlist` or +`open` only when you intentionally want other chats to trigger the agent. + +Voice transcription is enabled in the sample env. The image installs `ffmpeg` and +the Talon `speech` extra so inbound WhatsApp voice notes are transcribed locally +with NVIDIA Parakeet through Transformers before reaching the agent. The first +voice message can be slow because the ASR model is downloaded lazily. Set +`DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_DEVICE=cuda` on GPU-enabled hosts. + +### Telegram + +Create a Telegram bot with BotFather, add its token to `.env`, and enable the +Telegram channel: + +```bash +DEEPAGENTS_TALON_TELEGRAM_ENABLED=true +DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN= +DEEPAGENTS_TALON_TELEGRAM_EXPOSURE=allowlist +DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_USERS=123456789 +DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_CHATS=-1001234567890 +``` + +Use `DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_USERS` for private bot DMs from specific +Telegram user IDs. Use `DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_CHATS` for channel +posts from specific Telegram channel chat IDs. Channel chat IDs are usually +negative and often start with `-100`. + +To process Telegram channel posts, add the bot to the channel with permission to +read posts. If you only want private DMs, leave `ALLOWLIST_CHATS` empty. If you +only want channel posts, leave `ALLOWLIST_USERS` empty. + +## Example Env Values + +The tracked `.env.example` uses placeholder-only values. Keep real provider keys +and bot tokens in your local `.env`, which is ignored by git. + +```bash +AGENT_ASSISTANT_ID=talon-docker-local +AGENT_MODEL= + +DEEPAGENTS_TALON_WHATSAPP_ENABLED=true +DEEPAGENTS_TALON_TELEGRAM_ENABLED=false + +DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN= +DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_USERS= +DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_CHATS= + +LANGSMITH_TRACING=false +LANGSMITH_API_KEY= +``` + +`AGENT_MODEL` selects the Deep Agents chat model. If it is unset, Talon runs the +echo runtime for smoke tests and replies with the inbound text unchanged. + +The Docker example overrides `DEEPAGENTS_TALON_HOME` to +`/workspace/.deepagents`, so cron jobs are stored at +`~/agent-workspace/.deepagents//cron/jobs.json`. Assistant Markdown +image/video attachments must use relative paths inside +`DEEPAGENTS_TALON_OUTBOUND_MEDIA_DIR`, or inside `DEEPAGENTS_TALON_WORKSPACE` +when no outbound media directory is configured. + +Set `LANGSMITH_TRACING=true` and `LANGSMITH_API_KEY` to trace each channel or +cron-triggered run. `LANGSMITH_PROJECT` defaults to `deepagents-talon`. + +## Local Run Without Docker + +```bash +cp .env.example .env +set -a +. ./.env +set +a + +cd ../../libs/talon/deepagents_talon/channels/whatsapp_bridge +sfw npm install + +cd ../../../.. +sfw uv sync --directory libs/talon --extra speech +cp examples/talon-docker/AGENTS.md ~/.deepagents/talon-docker-local/agent/AGENTS.md +export DEEPAGENTS_TALON_WORKSPACE=~/agent-workspace +uv run --directory libs/talon deepagents-talon +``` + +## Exposure Reference + +WhatsApp exposure: + +- `DEEPAGENTS_TALON_WHATSAPP_EXPOSURE=self` allows only messages from the paired + account. +- `DEEPAGENTS_TALON_WHATSAPP_EXPOSURE=allowlist` allows chats in + `DEEPAGENTS_TALON_WHATSAPP_ALLOWLIST_CHATS` or messages matching + `DEEPAGENTS_TALON_WHATSAPP_MENTION_PATTERNS`. +- `DEEPAGENTS_TALON_WHATSAPP_EXPOSURE=open` allows every inbound WhatsApp + message and requires `DEEPAGENTS_TALON_WHATSAPP_OPEN_ACK=allow-arbitrary-senders`. + +Telegram exposure: + +- `DEEPAGENTS_TALON_TELEGRAM_EXPOSURE=self` allows only messages from + `DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID`. +- `DEEPAGENTS_TALON_TELEGRAM_EXPOSURE=allowlist` allows private DMs from + `DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_USERS`, channel posts from + `DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_CHATS`, or messages matching + `DEEPAGENTS_TALON_TELEGRAM_MENTION_PATTERNS`. +- `DEEPAGENTS_TALON_TELEGRAM_EXPOSURE=open` allows every inbound Telegram + message and requires `DEEPAGENTS_TALON_TELEGRAM_OPEN_ACK=allow-arbitrary-senders`. + +Cron jobs are stored in the assistant state directory at `cron/jobs.json`. +Scheduler ticks, dispatch, success/failure, and delivery outcomes are logged as +`talon_event` JSON records. + +## Resources + +- [LangChain Academy](https://academy.langchain.com/) - Comprehensive, free + courses on LangChain libraries and products, made by the LangChain team. +- [Code of Conduct](https://github.com/langchain-ai/langchain/?tab=coc-ov-file) + - community guidelines and standards diff --git a/examples/talon-whatsapp/docker-compose.yml b/examples/talon-docker/docker-compose.yml similarity index 57% rename from examples/talon-whatsapp/docker-compose.yml rename to examples/talon-docker/docker-compose.yml index 73d09d6ed2d..b4d812c360d 100644 --- a/examples/talon-whatsapp/docker-compose.yml +++ b/examples/talon-docker/docker-compose.yml @@ -2,8 +2,8 @@ services: talon: build: context: ../.. - dockerfile: examples/talon-whatsapp/Dockerfile - image: deepagents-talon-whatsapp:local + dockerfile: examples/talon-docker/Dockerfile + image: deepagents-talon:local working_dir: /workspace env_file: - .env @@ -11,13 +11,15 @@ services: DEEPAGENTS_TALON_HOME: /workspace/.deepagents DEEPAGENTS_TALON_WORKSPACE: /workspace DEEPAGENTS_TALON_WHATSAPP_SESSION_DIR: /workspace/.deepagents/whatsapp-session + DEEPAGENTS_TALON_TELEGRAM_SESSION_DIR: /workspace/.deepagents/telegram-session DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_ENABLED: ${DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_ENABLED:-true} DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_DEVICE: ${DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_DEVICE:-cpu} volumes: - ${HOME}/agent-workspace:/workspace command: > bash -c " - mkdir -p /workspace/.deepagents/$${AGENT_ASSISTANT_ID}/agent && - cp /opt/deepagents-talon/AGENTS.md /workspace/.deepagents/$${AGENT_ASSISTANT_ID}/agent/AGENTS.md && - /opt/deepagents-talon-venv/bin/deepagents-talon --whatsapp + assistant_id=\"$${AGENT_ASSISTANT_ID:-default}\" && + mkdir -p \"/workspace/.deepagents/$${assistant_id}/agent\" && + cp /opt/deepagents-talon/AGENTS.md \"/workspace/.deepagents/$${assistant_id}/agent/AGENTS.md\" && + exec /opt/deepagents-talon-venv/bin/deepagents-talon " diff --git a/examples/talon-whatsapp/.env.example b/examples/talon-whatsapp/.env.example deleted file mode 100644 index 494323b64b7..00000000000 --- a/examples/talon-whatsapp/.env.example +++ /dev/null @@ -1,25 +0,0 @@ -# Required assistant identity and model. -AGENT_ASSISTANT_ID=whatsapp-local -AGENT_MODEL=openai:gpt-5.2 -DEEPAGENTS_TALON_CONTEXT_SIZE=75000 -OPENAI_API_KEY= - -# Optional LangSmith tracing. Traces are emitted only when both are set. -LANGSMITH_TRACING=false -LANGSMITH_API_KEY= -LANGSMITH_PROJECT=deepagents-talon - -# WhatsApp channel. -DEEPAGENTS_TALON_WHATSAPP_ENABLED=true -DEEPAGENTS_TALON_WHATSAPP_EXPOSURE=self -DEEPAGENTS_TALON_WHATSAPP_OPERATOR_ID= -DEEPAGENTS_TALON_WHATSAPP_ALLOWLIST_CHATS= -DEEPAGENTS_TALON_WHATSAPP_MENTION_PATTERNS= -DEEPAGENTS_TALON_WHATSAPP_BRIDGE_HOST=127.0.0.1 -DEEPAGENTS_TALON_WHATSAPP_BRIDGE_PORT=3000 -DEEPAGENTS_TALON_WHATSAPP_START_BRIDGE=true - -# Voice transcription. -# Uses local NVIDIA Parakeet through Transformers. First use downloads the model. -DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_ENABLED=true -DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_DEVICE=cpu diff --git a/examples/talon-whatsapp/README.md b/examples/talon-whatsapp/README.md deleted file mode 100644 index 3ef5db494d2..00000000000 --- a/examples/talon-whatsapp/README.md +++ /dev/null @@ -1,62 +0,0 @@ -# Talon WhatsApp Example - -This example runs one Talon host process with the WhatsApp bridge subprocess in the same container. The bridge binds to loopback inside the container and the host `~/agent-workspace/` directory is mounted at `/workspace`. - -> **Experimental:** Talon is an experimental runtime and is subject to change or removal at any time. - -## Run - -```bash -cp .env.example .env -mkdir -p ~/agent-workspace -# Fill AGENT_MODEL provider credentials, then build once and run: -docker compose build -docker compose up -``` - -Scan the QR code printed by the bridge. The default exposure mode is `self`, so only messages sent by the paired WhatsApp account trigger the agent. Use `allowlist` or `open` only when you intentionally want other chats to trigger the agent. - -Voice transcription is enabled in `.env.example`. The Docker example installs `ffmpeg` and the Talon `speech` extra so inbound WhatsApp voice notes are transcribed locally with NVIDIA Parakeet through Transformers before reaching the agent. The first voice message can be slow because the ASR model is downloaded lazily. Set `DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_DEVICE=cuda` when running on a GPU-enabled host. - -Cron records, downloaded inbound media, and WhatsApp session state persist under `~/agent-workspace/.deepagents/`. The agent's default working directory is `/workspace`, so files it creates are written into `~/agent-workspace/` on the host. - -The image installs the Talon package at build time. Rebuild after changing the Dockerfile, system packages, Node dependencies, or Talon Python dependencies. - -## Local Run Without Docker - -```bash -cp .env.example .env -set -a -. ./.env -set +a - -cd ../../libs/talon/deepagents_talon/channels/whatsapp_bridge -npm install - -cd ../../../.. -uv sync --directory libs/talon --extra speech -cp examples/talon-whatsapp/AGENTS.md ~/.deepagents/whatsapp-local/agent/AGENTS.md -export DEEPAGENTS_TALON_WORKSPACE=~/agent-workspace -uv run --directory libs/talon deepagents-talon --whatsapp -``` - -## Environment Reference - -`AGENT_ASSISTANT_ID` names the local state directory under `~/.deepagents/`. `AGENT_MODEL` selects the Deep Agents chat model. If it is unset, Talon runs the echo runtime for smoke tests. - -The Docker example overrides `DEEPAGENTS_TALON_HOME` to `/workspace/.deepagents`, so cron jobs are stored at `~/agent-workspace/.deepagents//cron/jobs.json`. Assistant Markdown image/video attachments must use relative paths inside `DEEPAGENTS_TALON_OUTBOUND_MEDIA_DIR`, or inside `DEEPAGENTS_TALON_WORKSPACE` when no outbound media directory is configured. - -Set `LANGSMITH_TRACING=true` and `LANGSMITH_API_KEY` to trace each channel or cron-triggered run. `LANGSMITH_PROJECT` defaults to `deepagents-talon`. - -WhatsApp exposure: - -- `DEEPAGENTS_TALON_WHATSAPP_EXPOSURE=self` allows only messages from the paired account. -- `DEEPAGENTS_TALON_WHATSAPP_EXPOSURE=allowlist` allows chats in `DEEPAGENTS_TALON_WHATSAPP_ALLOWLIST_CHATS` or messages matching `DEEPAGENTS_TALON_WHATSAPP_MENTION_PATTERNS`. -- `DEEPAGENTS_TALON_WHATSAPP_EXPOSURE=open` allows every inbound WhatsApp message. - -Cron jobs are stored in the assistant state directory at `cron/jobs.json`. Scheduler ticks, dispatch, success/failure, and delivery outcomes are logged as `talon_event` JSON records. - -## Resources - -- [LangChain Academy](https://academy.langchain.com/) — Comprehensive, free courses on LangChain libraries and products, made by the LangChain team. -- [Code of Conduct](https://github.com/langchain-ai/langchain/?tab=coc-ov-file) — community guidelines and standards diff --git a/libs/talon/README.md b/libs/talon/README.md index 04db1aafafc..bb839aac105 100644 --- a/libs/talon/README.md +++ b/libs/talon/README.md @@ -16,7 +16,7 @@ Talon currently includes: ```bash uv sync --group test -AGENT_ASSISTANT_ID=local AGENT_MODEL=openai:gpt-5.2 uv run deepagents-talon --once +AGENT_ASSISTANT_ID=local AGENT_MODEL=: uv run deepagents-talon --once ``` If `AGENT_MODEL` is unset, Talon starts with the echo runtime. This is useful for checking host lifecycle and channel wiring without provider credentials. @@ -58,8 +58,8 @@ cd ../../.. DEEPAGENTS_TALON_WHATSAPP_ENABLED=true \ DEEPAGENTS_TALON_WHATSAPP_START_BRIDGE=true \ -AGENT_ASSISTANT_ID=whatsapp-local \ -AGENT_MODEL=openai:gpt-5.2 \ +AGENT_ASSISTANT_ID=talon-docker-local \ +AGENT_MODEL=: \ uv run deepagents-talon --whatsapp ``` @@ -80,7 +80,7 @@ DEEPAGENTS_TALON_WHATSAPP_EXPOSURE=open DEEPAGENTS_TALON_WHATSAPP_OPEN_ACK=allow-arbitrary-senders ``` -See `../../examples/talon-whatsapp/` for a runnable Docker Compose topology and `.env` reference. +See `../../examples/talon-docker/` for a runnable Docker Compose topology and `.env` reference. ## Telegram @@ -93,7 +93,7 @@ DEEPAGENTS_TALON_TELEGRAM_EXPOSURE=allowlist \ DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_USERS=123456789 \ DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_CHATS=-1001234567890 \ AGENT_ASSISTANT_ID=telegram-local \ -AGENT_MODEL=openai:gpt-5.2 \ +AGENT_MODEL=: \ uv run deepagents-talon --telegram ``` From d2b727d05b3cb3cea4fd42ea64162d22fbb6c512 Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sat, 20 Jun 2026 10:19:47 -0700 Subject: [PATCH 05/48] test(talon): wait for Telegram media dispatch --- libs/talon/tests/channels/test_telegram.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/libs/talon/tests/channels/test_telegram.py b/libs/talon/tests/channels/test_telegram.py index 4089f7e2526..86f27aef9c7 100644 --- a/libs/talon/tests/channels/test_telegram.py +++ b/libs/talon/tests/channels/test_telegram.py @@ -990,9 +990,10 @@ async def test_channel_loads_persisted_offset_on_start(tmp_path: Path) -> None: async def _wait_for_received(messages: list[ChannelMessage], count: int) -> None: - for _ in range(100): + deadline = asyncio.get_running_loop().time() + 2 + while asyncio.get_running_loop().time() < deadline: if len(messages) >= count: return - await asyncio.sleep(0) + await asyncio.sleep(0.01) msg = f"received {len(messages)} message(s), expected {count}" raise AssertionError(msg) From 6ae8b6908d13ba4f980c9e86a42c748aeed63f79 Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sat, 20 Jun 2026 10:23:26 -0700 Subject: [PATCH 06/48] fix(talon): address Telegram review feedback --- examples/talon-docker/README.md | 4 +- .../deepagents_talon/channels/telegram.py | 16 +++++-- libs/talon/tests/channels/test_telegram.py | 43 +++++++++++++++++++ 3 files changed, 58 insertions(+), 5 deletions(-) diff --git a/examples/talon-docker/README.md b/examples/talon-docker/README.md index 38f6b0228bd..c0798601faa 100644 --- a/examples/talon-docker/README.md +++ b/examples/talon-docker/README.md @@ -111,10 +111,10 @@ set -a set +a cd ../../libs/talon/deepagents_talon/channels/whatsapp_bridge -sfw npm install +npm install cd ../../../.. -sfw uv sync --directory libs/talon --extra speech +uv sync --directory libs/talon --extra speech cp examples/talon-docker/AGENTS.md ~/.deepagents/talon-docker-local/agent/AGENTS.md export DEEPAGENTS_TALON_WORKSPACE=~/agent-workspace uv run --directory libs/talon deepagents-talon diff --git a/libs/talon/deepagents_talon/channels/telegram.py b/libs/talon/deepagents_talon/channels/telegram.py index a9795316f41..ab8f38fc6bb 100644 --- a/libs/talon/deepagents_talon/channels/telegram.py +++ b/libs/talon/deepagents_talon/channels/telegram.py @@ -463,9 +463,6 @@ async def _poll_updates(self) -> None: allowed_updates=_ALLOWED_UPDATES, ) updates = _extract_updates(payload) - if updates: - self._offset = cast("int", updates[-1]["update_id"]) + 1 - _save_offset(self.config.offset_file, self._offset) self._status = ChannelStatus( provider="telegram", connected=True, @@ -474,6 +471,7 @@ async def _poll_updates(self) -> None: for update in updates: message = _parse_update(update) if message is None: + self._commit_update_offset(update) continue message = _with_from_self(message, self._bot_id) if not _allows_telegram_message( @@ -486,9 +484,11 @@ async def _poll_updates(self) -> None: message.message_id, message.conversation_id, ) + self._commit_update_offset(update) continue message = await self._prepare_inbound_media(message) await self._dispatch(message) + self._commit_update_offset(update) except (TelegramError, urllib.error.URLError, TimeoutError): logger.exception("Telegram long-polling error; retrying after interval") self._status = ChannelStatus( @@ -500,6 +500,16 @@ async def _poll_updates(self) -> None: raise await asyncio.sleep(self.config.poll_interval_seconds) + def _commit_update_offset(self, update: Mapping[str, object]) -> None: + update_id = update.get("update_id") + if not isinstance(update_id, int): + return + next_offset = update_id + 1 + if next_offset <= self._offset: + return + self._offset = next_offset + _save_offset(self.config.offset_file, self._offset) + async def _dispatch(self, message: ChannelMessage) -> None: if self._handler is None: logger.warning("Dropping Telegram message because no handler is registered") diff --git a/libs/talon/tests/channels/test_telegram.py b/libs/talon/tests/channels/test_telegram.py index 86f27aef9c7..3107434a8ad 100644 --- a/libs/talon/tests/channels/test_telegram.py +++ b/libs/talon/tests/channels/test_telegram.py @@ -989,6 +989,49 @@ async def test_channel_loads_persisted_offset_on_start(tmp_path: Path) -> None: assert get_updates_calls[0][1]["offset"] == 100 +async def test_channel_does_not_persist_failed_media_update_offset(tmp_path: Path) -> None: + class FailingGetFileTransport(RecordingTransport): + async def call(self, method: str, **params: object) -> object: + if method == "getFile": + self.calls.append((method, dict(params))) + msg = "temporary getFile failure" + raise TelegramError(msg) + return await super().call(method, **params) + + transport = FailingGetFileTransport( + updates=[ + _make_update(update_id=10, chat_id=111, sender_id=111, text="before media"), + _make_update( + update_id=11, + chat_id=111, + sender_id=111, + text="media", + photo=[{"file_id": "photo123", "file_size": 100}], + ), + ], + ) + config = _make_config(tmp_path, operator_id="111") + channel = TelegramChannel(config, transport=cast("TelegramTransport", transport)) + received: list[ChannelMessage] = [] + + async def record(message: ChannelMessage) -> None: + received.append(message) + + channel.set_message_handler(record) + + await channel.start() + deadline = asyncio.get_running_loop().time() + 2 + while asyncio.get_running_loop().time() < deadline: + status = await channel.status() + if status.detail == "polling error": + break + await asyncio.sleep(0.01) + await channel.stop() + + assert [msg.text for msg in received] == ["before media"] + assert _load_offset(config.offset_file) == 11 + + async def _wait_for_received(messages: list[ChannelMessage], count: int) -> None: deadline = asyncio.get_running_loop().time() + 2 while asyncio.get_running_loop().time() < deadline: From b7f0b3890bdcc8857d7b3280664e175681cd3a3a Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sat, 20 Jun 2026 10:25:53 -0700 Subject: [PATCH 07/48] docs(talon): clarify local Talon commands --- libs/talon/README.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/libs/talon/README.md b/libs/talon/README.md index bb839aac105..d117269c1fc 100644 --- a/libs/talon/README.md +++ b/libs/talon/README.md @@ -14,7 +14,11 @@ Talon currently includes: ## Quickstart +Run the commands in this README from `libs/talon`. From the repository root, +prefix `uv` commands with `--directory libs/talon`. + ```bash +cd libs/talon uv sync --group test AGENT_ASSISTANT_ID=local AGENT_MODEL=: uv run deepagents-talon --once ``` @@ -97,6 +101,19 @@ AGENT_MODEL=: \ uv run deepagents-talon --telegram ``` +From the repository root, run the same host with: + +```bash +DEEPAGENTS_TALON_TELEGRAM_ENABLED=true \ +DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN=... \ +DEEPAGENTS_TALON_TELEGRAM_EXPOSURE=allowlist \ +DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_USERS=123456789 \ +DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_CHATS=-1001234567890 \ +AGENT_ASSISTANT_ID=telegram-local \ +AGENT_MODEL=: \ +uv run --directory libs/talon deepagents-talon --telegram +``` + In `allowlist` mode, `DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_USERS` allows private bot DMs from specific Telegram user IDs, while `DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_CHATS` allows channel posts from specific channel chat IDs. If `AGENT_MODEL`, `DEEPAGENTS_TALON_MODEL`, and `DEEPAGENTS_TALON_FLEET_DIR` are all unset, Talon uses the echo runtime and replies with the inbound text unchanged. ## Tracing From 7a5781e632fdc6eeccbdd6b93d6b360f32b3f431 Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sat, 20 Jun 2026 10:41:04 -0700 Subject: [PATCH 08/48] fix(talon): support `/new` command for channel threads --- libs/talon/deepagents_talon/host.py | 98 ++++++++++++++++++++++++----- libs/talon/tests/test_host.py | 82 ++++++++++++++++++++++++ 2 files changed, 165 insertions(+), 15 deletions(-) diff --git a/libs/talon/deepagents_talon/host.py b/libs/talon/deepagents_talon/host.py index a6494f2a96a..6a3f3197d9a 100644 --- a/libs/talon/deepagents_talon/host.py +++ b/libs/talon/deepagents_talon/host.py @@ -50,10 +50,13 @@ logger = logging.getLogger(__name__) _STOP_COMMAND = "/stop" +_NEW_COMMAND = "/new" +_NEW_CONVERSATION_MESSAGE = "Started a fresh conversation." _APPROVE_REPLIES = frozenset({"approve", "approved", "yes", "y"}) _DENY_REPLIES = frozenset({"deny", "denied", "reject", "rejected", "no", "n"}) _OUTBOUND_MEDIA_DIR_ENV = "DEEPAGENTS_TALON_OUTBOUND_MEDIA_DIR" _WORKSPACE_ENV = "DEEPAGENTS_TALON_WORKSPACE" +_RESET_THREAD_SEPARATOR = ":talon-reset:" @dataclass(slots=True) @@ -90,6 +93,7 @@ def __init__( self._locks: defaultdict[str, asyncio.Lock] = defaultdict(asyncio.Lock) self._tasks: dict[str, asyncio.Task[None]] = {} self._conversation_tasks: defaultdict[str, set[asyncio.Task[None]]] = defaultdict(set) + self._conversation_resets: defaultdict[str, int] = defaultdict(int) self._pending_tool_approvals: dict[str, _PendingToolApproval] = {} self._stopped = asyncio.Event() self._running = False @@ -160,22 +164,39 @@ async def receive_message(self, channel: ChannelAdapter, message: ChannelMessage channel: Channel that delivered the message. message: Inbound message to process. """ - if message.text.strip().lower() == _STOP_COMMAND: - await self._cancel_conversation(channel, message.conversation_id) + command = _command_name(message.text) + channel_conversation_id = message.conversation_id + agent_conversation_id = self._agent_conversation_id(channel_conversation_id) + + if command == _NEW_COMMAND: + await self._start_new_conversation(channel, channel_conversation_id) return - pending = self._pending_tool_approvals.get(message.conversation_id) + if command == _STOP_COMMAND: + await self._cancel_conversation( + channel, + agent_conversation_id, + reply_conversation_id=channel_conversation_id, + ) + return + + pending = self._pending_tool_approvals.get(agent_conversation_id) if pending is not None: await self._handle_tool_approval_reply(channel, message, pending) return task = asyncio.create_task( - self._run_agent_turn(channel, message), - name=f"talon:{message.conversation_id}", + self._run_agent_turn(channel, message, agent_conversation_id), + name=f"talon:{agent_conversation_id}", ) - self._track_conversation_task(message.conversation_id, task) + self._track_conversation_task(agent_conversation_id, task) - async def _run_agent_turn(self, channel: ChannelAdapter, message: ChannelMessage) -> None: + async def _run_agent_turn( + self, + channel: ChannelAdapter, + message: ChannelMessage, + agent_conversation_id: str, + ) -> None: message = await transcribe_voice_message(self.voice_transcriber, message) message = _prepare_inbound_message(message) provider = await _channel_provider(channel) @@ -185,8 +206,8 @@ async def _run_agent_turn(self, channel: ChannelAdapter, message: ChannelMessage "message_id": message.message_id, **message.metadata, } - origin_conversation_id = message.metadata.get("chat_id_from") - if isinstance(origin_conversation_id, str) and origin_conversation_id: + origin_conversation_id = _origin_conversation_id(message) + if origin_conversation_id != agent_conversation_id: metadata["origin_conversation_id"] = origin_conversation_id content = build_model_content(message.text, dict(message.metadata)) if content != message.text: @@ -194,12 +215,13 @@ async def _run_agent_turn(self, channel: ChannelAdapter, message: ChannelMessage await _send_typing(channel, message.conversation_id) result = await self._invoke_agent( - conversation_id=message.conversation_id, + conversation_id=agent_conversation_id, text=message.text, metadata=metadata, approval_handler=lambda approval: self._request_tool_approval( channel, approval, + reply_conversation_id=message.conversation_id, sender_id=message.sender_id, ), ) @@ -214,13 +236,15 @@ async def run_scheduled_job(self, job: CronJob) -> str: Returns: Agent text output for scheduler delivery handling. """ + conversation_id = self._agent_conversation_id(job.origin.conversation_id) result = await self._invoke_agent( - conversation_id=job.origin.conversation_id, + conversation_id=conversation_id, text=job.prompt, metadata={ "channel": job.origin.channel, "cron_job_id": job.id, "cron_job_name": job.name, + "origin_conversation_id": job.origin.conversation_id, "cron_origin_message_id": job.origin.message_id, "trigger": "cron", }, @@ -284,11 +308,32 @@ async def _invoke_agent( if self._tasks.get(conversation_id) is task: del self._tasks[conversation_id] + async def _start_new_conversation( + self, + channel: ChannelAdapter, + conversation_id: str, + ) -> None: + current_conversation_id = self._agent_conversation_id(conversation_id) + await self._cancel_conversation_tasks(current_conversation_id) + self._conversation_resets[conversation_id] += 1 + await channel.send_message(conversation_id, _NEW_CONVERSATION_MESSAGE) + async def _cancel_conversation( self, channel: ChannelAdapter, conversation_id: str, + *, + reply_conversation_id: str | None = None, ) -> None: + target_conversation_id = reply_conversation_id or conversation_id + cancelled = await self._cancel_conversation_tasks(conversation_id) + if not cancelled: + await channel.send_message(target_conversation_id, "No in-flight run to stop.") + return + + await channel.send_message(target_conversation_id, "Stopped current run.") + + async def _cancel_conversation_tasks(self, conversation_id: str) -> bool: tasks = { task for task in { @@ -298,13 +343,18 @@ async def _cancel_conversation( if task is not None and not task.done() } if not tasks: - await channel.send_message(conversation_id, "No in-flight run to stop.") - return + return False for task in tasks: task.cancel() await asyncio.gather(*tasks, return_exceptions=True) - await channel.send_message(conversation_id, "Stopped current run.") + return True + + def _agent_conversation_id(self, conversation_id: str) -> str: + reset = self._conversation_resets[conversation_id] + if reset == 0: + return conversation_id + return f"{conversation_id}{_RESET_THREAD_SEPARATOR}{reset}" async def _cancel_all(self) -> None: tasks = { @@ -331,6 +381,7 @@ async def _request_tool_approval( channel: ChannelAdapter, approval: ToolApprovalRequest, *, + reply_conversation_id: str, sender_id: str | None, ) -> ToolApprovalDecision: loop = asyncio.get_running_loop() @@ -339,7 +390,7 @@ async def _request_tool_approval( self._pending_tool_approvals[approval.conversation_id] = pending try: await channel.send_message( - approval.conversation_id, + reply_conversation_id, _format_tool_approval_prompt(approval), ) return await future @@ -464,6 +515,23 @@ def _prepare_inbound_message(message: ChannelMessage) -> ChannelMessage: ) +def _command_name(text: str) -> str | None: + parts = text.strip().split(maxsplit=1) + if not parts: + return None + first = parts[0].lower() + if not first.startswith("/"): + return None + return first.split("@", maxsplit=1)[0] + + +def _origin_conversation_id(message: ChannelMessage) -> str: + origin = message.metadata.get("chat_id_from") + if isinstance(origin, str) and origin: + return origin + return message.conversation_id + + def _outbound_media_from_refs( refs: list[MarkdownMediaRef], cleaned_text: str, diff --git a/libs/talon/tests/test_host.py b/libs/talon/tests/test_host.py index 1c4fcf420c0..878713808da 100644 --- a/libs/talon/tests/test_host.py +++ b/libs/talon/tests/test_host.py @@ -83,6 +83,25 @@ async def invoke(self, request: AgentRequest) -> AgentResult: return AgentResult(text=f"reply:{request.text}") +class HistoryAgent: + def __init__(self) -> None: + self.history: dict[str, list[str]] = {} + self.requests: list[AgentRequest] = [] + + async def start(self) -> None: + pass + + async def stop(self) -> None: + pass + + async def invoke(self, request: AgentRequest) -> AgentResult: + self.requests.append(request) + history = self.history.setdefault(request.conversation_id, []) + seen = len(history) + history.append(request.text) + return AgentResult(text=f"seen:{seen}") + + class VoiceTranscriber: async def transcribe(self, message: ChannelMessage) -> str | None: del message @@ -183,6 +202,69 @@ async def test_stop_cancels_in_flight_conversation(tmp_path: Path) -> None: assert channel.sent == [("chat", "Stopped current run.")] +async def test_new_command_starts_fresh_conversation_thread(tmp_path: Path) -> None: + channel = RecordingChannel() + agent = HistoryAgent() + host = TalonHost(config=_config(tmp_path), agent=agent, channels=[channel]) + await host.start() + + await host.receive_message(channel, ChannelMessage(conversation_id="chat", text="first")) + await _wait_for_sent_count(channel, 1) + await host.receive_message(channel, ChannelMessage(conversation_id="chat", text="/new")) + await host.receive_message(channel, ChannelMessage(conversation_id="chat", text="second")) + await _wait_for_sent_count(channel, 3) + await host.stop() + + assert [request.text for request in agent.requests] == ["first", "second"] + assert agent.requests[0].conversation_id == "chat" + assert agent.requests[1].conversation_id.startswith("chat:talon-reset:") + assert channel.sent == [ + ("chat", "seen:0"), + ("chat", "Started a fresh conversation."), + ("chat", "seen:0"), + ] + + +async def test_new_command_accepts_telegram_bot_command_suffix(tmp_path: Path) -> None: + channel = RecordingChannel() + agent = HistoryAgent() + host = TalonHost(config=_config(tmp_path), agent=agent, channels=[channel]) + await host.start() + + await host.receive_message(channel, ChannelMessage(conversation_id="chat", text="/new@TestBot")) + await host.receive_message(channel, ChannelMessage(conversation_id="chat", text="hello")) + await _wait_for_sent_count(channel, 2) + await host.stop() + + assert [request.text for request in agent.requests] == ["hello"] + assert agent.requests[0].conversation_id.startswith("chat:talon-reset:") + assert channel.sent == [ + ("chat", "Started a fresh conversation."), + ("chat", "seen:0"), + ] + + +async def test_new_command_cancels_in_flight_conversation(tmp_path: Path) -> None: + channel = RecordingChannel() + agent = BlockingAgent() + host = TalonHost(config=_config(tmp_path), agent=agent, channels=[channel]) + await host.start() + + await host.receive_message(channel, ChannelMessage(conversation_id="chat", text="block")) + await _wait_for_request(agent, "block") + await host.receive_message(channel, ChannelMessage(conversation_id="chat", text="/new")) + await host.receive_message(channel, ChannelMessage(conversation_id="chat", text="second")) + await _wait_for_sent_count(channel, 2) + await host.stop() + + assert [request.text for request in agent.requests] == ["block", "second"] + assert agent.requests[1].conversation_id.startswith("chat:talon-reset:") + assert channel.sent == [ + ("chat", "Started a fresh conversation."), + ("chat", "reply:second"), + ] + + async def test_host_sends_markdown_media_refs_as_channel_media(tmp_path: Path) -> None: channel = RecordingChannel() workspace = tmp_path / "workspace" From d9148d9daae57ef8f25070473ea76f8ea9a7e8be Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sat, 20 Jun 2026 11:04:46 -0700 Subject: [PATCH 09/48] fix(talon): cap channel media size --- libs/talon/README.md | 6 +- libs/talon/deepagents_talon/channels/base.py | 66 +++++++++- .../deepagents_talon/channels/telegram.py | 81 ++++++++++-- .../deepagents_talon/channels/whatsapp.py | 107 +++++++++++++++- .../channels/whatsapp_bridge/bridge.js | 12 +- libs/talon/tests/channels/test_base.py | 23 ++++ libs/talon/tests/channels/test_telegram.py | 119 +++++++++++++++++- libs/talon/tests/channels/test_whatsapp.py | 109 +++++++++++++++- 8 files changed, 501 insertions(+), 22 deletions(-) diff --git a/libs/talon/README.md b/libs/talon/README.md index d117269c1fc..cd2c47109b1 100644 --- a/libs/talon/README.md +++ b/libs/talon/README.md @@ -67,7 +67,7 @@ AGENT_MODEL=: \ uv run deepagents-talon --whatsapp ``` -The bridge prints a QR code during pairing. By default, inbound exposure is `self`, so only messages from the paired account trigger the agent. Configure `DEEPAGENTS_TALON_WHATSAPP_EXPOSURE=allowlist` with `DEEPAGENTS_TALON_WHATSAPP_ALLOWLIST_CHATS` or `DEEPAGENTS_TALON_WHATSAPP_MENTION_PATTERNS` to allow specific chats. Outbound WhatsApp messages include a `deepagents bot` header by default so self-message conversations clearly distinguish agent replies from operator messages. Set `DEEPAGENTS_TALON_WHATSAPP_BOT_HEADER` to customize that label. Markdown image/video references in assistant replies may attach files only when they are relative paths inside `DEEPAGENTS_TALON_OUTBOUND_MEDIA_DIR`, or inside `DEEPAGENTS_TALON_WORKSPACE` when no outbound media directory is configured. +The bridge prints a QR code during pairing. By default, inbound exposure is `self`, so only messages from the paired account trigger the agent. Configure `DEEPAGENTS_TALON_WHATSAPP_EXPOSURE=allowlist` with `DEEPAGENTS_TALON_WHATSAPP_ALLOWLIST_CHATS` or `DEEPAGENTS_TALON_WHATSAPP_MENTION_PATTERNS` to allow specific chats. Outbound WhatsApp messages include a `deepagents bot` header by default so self-message conversations clearly distinguish agent replies from operator messages. Set `DEEPAGENTS_TALON_WHATSAPP_BOT_HEADER` to customize that label. Markdown image/video references in assistant replies may attach files only when they are relative paths inside `DEEPAGENTS_TALON_OUTBOUND_MEDIA_DIR`, or inside `DEEPAGENTS_TALON_WORKSPACE` when no outbound media directory is configured. `DEEPAGENTS_TALON_MAX_MEDIA_BYTES` caps inbound and outbound channel media across providers and defaults to `1073741824` (1 GiB). Inbound voice transcription is opt-in: @@ -114,7 +114,7 @@ AGENT_MODEL=: \ uv run --directory libs/talon deepagents-talon --telegram ``` -In `allowlist` mode, `DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_USERS` allows private bot DMs from specific Telegram user IDs, while `DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_CHATS` allows channel posts from specific channel chat IDs. If `AGENT_MODEL`, `DEEPAGENTS_TALON_MODEL`, and `DEEPAGENTS_TALON_FLEET_DIR` are all unset, Talon uses the echo runtime and replies with the inbound text unchanged. +In `allowlist` mode, `DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_USERS` allows private bot DMs from specific Telegram user IDs, while `DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_CHATS` allows channel posts from specific channel chat IDs. `DEEPAGENTS_TALON_MAX_MEDIA_BYTES` caps inbound and outbound channel media across providers and defaults to `1073741824` (1 GiB); Telegram's smaller Bot API upload limits still apply. If `AGENT_MODEL`, `DEEPAGENTS_TALON_MODEL`, and `DEEPAGENTS_TALON_FLEET_DIR` are all unset, Talon uses the echo runtime and replies with the inbound text unchanged. ## Tracing @@ -177,7 +177,7 @@ Sensitive local state is stored under `~/.deepagents//` by default - `cron/jobs.json` stores cron prompts, origin conversation ids, message ids, run status, and errors. Active jobs are retained while enabled. Completed jobs are deleted on startup after `DEEPAGENTS_TALON_CRON_RETENTION_DAYS`, default `30`. - `channels/whatsapp/` stores WhatsApp `LocalAuth` credentials and Chromium profile state. These credentials are retained until the operator deletes the directory, because automatic deletion would silently unpair the channel. -- `media/inbound/` is reserved for downloaded inbound media. Files older than `DEEPAGENTS_TALON_INBOUND_MEDIA_RETENTION_HOURS`, default `24`, are deleted on startup. The WhatsApp bridge stores downloaded inbound media under the assistant's inbound media directory and passes local paths plus MIME metadata to the host. +- `media/inbound/` is reserved for downloaded inbound media. Files older than `DEEPAGENTS_TALON_INBOUND_MEDIA_RETENTION_HOURS`, default `24`, are deleted on startup. Inbound and outbound channel media are capped by `DEEPAGENTS_TALON_MAX_MEDIA_BYTES`, default `1073741824` (1 GiB). The WhatsApp bridge stores downloaded inbound media under the assistant's inbound media directory and passes local paths plus MIME metadata to the host. Conversation persistence is intentionally not durable yet. Runtime conversation state is in-memory unless a future backend explicitly adds thread persistence. diff --git a/libs/talon/deepagents_talon/channels/base.py b/libs/talon/deepagents_talon/channels/base.py index 51945f44836..5273ad16a3d 100644 --- a/libs/talon/deepagents_talon/channels/base.py +++ b/libs/talon/deepagents_talon/channels/base.py @@ -16,11 +16,14 @@ from deepagents_talon.media import resolve_bounded_media_path if TYPE_CHECKING: + from collections.abc import Mapping from pathlib import Path MAX_TEXT_CHARS = 4096 MAX_IMAGE_BYTES = 16 * 1024 * 1024 MAX_VIDEO_BYTES = 64 * 1024 * 1024 +DEFAULT_MAX_MEDIA_BYTES = 1024 * 1024 * 1024 +MAX_MEDIA_BYTES_ENV = "DEEPAGENTS_TALON_MAX_MEDIA_BYTES" _LINK_PATTERN = re.compile(r"\[([^\]]+)]\(([^)]+)\)") _HEADING_PATTERN = re.compile(r"^#{1,6}\s+", flags=re.MULTILINE) @@ -37,7 +40,7 @@ class ExposureMode(StrEnum): class ChannelMediaError(ValueError): - """Raised when outbound media cannot be sent safely.""" + """Raised when channel media cannot be handled safely.""" @dataclass(frozen=True, slots=True) @@ -119,13 +122,19 @@ def chunk_text(text: str, *, limit: int = MAX_TEXT_CHARS) -> list[str]: return chunks -def validate_media(media: ChannelMedia, *, root: Path | None = None) -> ChannelMedia: +def validate_media( + media: ChannelMedia, + *, + root: Path | None = None, + max_bytes: int | None = None, +) -> ChannelMedia: """Validate outbound media path, type, and size. Args: media: Media payload to validate. root: Optional directory that must contain the media after symlink resolution. + max_bytes: Optional global media size cap. Returns: The validated media payload. @@ -151,7 +160,60 @@ def validate_media(media: ChannelMedia, *, root: Path | None = None) -> ChannelM msg = f"media file type {detected!r} does not match requested type {media.media_type!r}" raise ChannelMediaError(msg) + return _validate_media_size(media, path=path, max_bytes=max_bytes) + + +def validate_media_size(path: Path, *, max_bytes: int) -> None: + """Validate a local media file against the configured global cap. + + Args: + path: Local media file to inspect. + max_bytes: Maximum allowed media file size. + + Raises: + ChannelMediaError: If the file exceeds `max_bytes`. + """ + size = path.stat().st_size + if size > max_bytes: + msg = f"media file is too large: {size} bytes exceeds {max_bytes}" + raise ChannelMediaError(msg) + + +def max_media_bytes_from_env(env: Mapping[str, str]) -> int: + """Return the configured global media cap. + + Args: + env: Environment variable mapping. + + Returns: + Maximum media bytes allowed for channel media. + + Raises: + ValueError: If the configured value is not a positive integer. + """ + value = env.get(MAX_MEDIA_BYTES_ENV) + if value is None: + return DEFAULT_MAX_MEDIA_BYTES + try: + parsed = int(value) + except ValueError as error: + msg = f"{MAX_MEDIA_BYTES_ENV} must be a positive integer byte count" + raise ValueError(msg) from error + if parsed < 1: + msg = f"{MAX_MEDIA_BYTES_ENV} must be a positive integer byte count" + raise ValueError(msg) + return parsed + + +def _validate_media_size( + media: ChannelMedia, + *, + path: Path, + max_bytes: int | None = None, +) -> ChannelMedia: limit = MAX_IMAGE_BYTES if media.media_type == "image" else MAX_VIDEO_BYTES + if max_bytes is not None: + limit = min(limit, max_bytes) size = path.stat().st_size if size > limit: msg = f"{media.media_type} media is too large: {size} bytes exceeds {limit}" diff --git a/libs/talon/deepagents_talon/channels/telegram.py b/libs/talon/deepagents_talon/channels/telegram.py index ab8f38fc6bb..2c466b2ad0d 100644 --- a/libs/talon/deepagents_talon/channels/telegram.py +++ b/libs/talon/deepagents_talon/channels/telegram.py @@ -18,11 +18,13 @@ from typing import TYPE_CHECKING, cast from deepagents_talon.channels.base import ( + DEFAULT_MAX_MEDIA_BYTES, MAX_TEXT_CHARS, ChannelExposure, ChannelMediaError, ExposureMode, chunk_text, + max_media_bytes_from_env, validate_media, ) from deepagents_talon.interfaces import ChannelMedia, ChannelMessage, ChannelStatus, MessageHandler @@ -77,6 +79,8 @@ class TelegramChannelConfig: poll_timeout_seconds: Long-polling timeout passed to getUpdates. poll_interval_seconds: Delay between getUpdates calls. request_timeout_seconds: Per-request HTTP timeout for Bot API calls. + max_media_bytes: Maximum media bytes allowed for inbound downloads and + outbound local files before provider-specific limits are applied. operator_id: Telegram user ID for the operator (self exposure mode). allowed_user_ids: Telegram user IDs allowed to trigger private chats in allowlist exposure mode. @@ -91,6 +95,7 @@ class TelegramChannelConfig: poll_timeout_seconds: float = DEFAULT_POLL_TIMEOUT_SECONDS poll_interval_seconds: float = DEFAULT_POLL_INTERVAL_SECONDS request_timeout_seconds: float = DEFAULT_REQUEST_TIMEOUT_SECONDS + max_media_bytes: int = DEFAULT_MAX_MEDIA_BYTES operator_id: str | None = None allowed_user_ids: frozenset[str] = field(default_factory=frozenset) @@ -150,6 +155,7 @@ def from_talon_config(cls, config: TalonConfig) -> TelegramChannelConfig: env.get("DEEPAGENTS_TALON_TELEGRAM_REQUEST_TIMEOUT_SECONDS"), DEFAULT_REQUEST_TIMEOUT_SECONDS, ), + max_media_bytes=max_media_bytes_from_env(env), operator_id=operator_id, allowed_user_ids=frozenset( _split_csv(env.get("DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_USERS", "")), @@ -358,7 +364,11 @@ async def send_media(self, conversation_id: str, media: ChannelMedia) -> None: Raises: ChannelMediaError: If the media is too large or invalid. """ - checked = validate_media(media, root=self.config.outbound_media_dir) + checked = validate_media( + media, + root=self.config.outbound_media_dir, + max_bytes=self.config.max_media_bytes, + ) _check_telegram_size(checked) caption = _escape_markdown_v2(checked.caption) if checked.caption else None if checked.media_type == "image": @@ -524,11 +534,28 @@ async def _prepare_inbound_media(self, message: ChannelMessage) -> ChannelMessag if self.config.inbound_media_dir is None: return message - destination = await self._download_inbound_media( - file_id, - media_type=media_type, - message_id=message.message_id, - ) + try: + destination = await self._download_inbound_media( + file_id, + media_type=media_type, + message_id=message.message_id, + ) + except ChannelMediaError as error: + logger.warning( + "Skipping Telegram inbound media for message %s: %s", + message.message_id, + error, + ) + metadata = dict(message.metadata) + metadata["has_media"] = False + metadata["media_error"] = str(error) + return ChannelMessage( + conversation_id=message.conversation_id, + text=message.text, + sender_id=message.sender_id, + message_id=message.message_id, + metadata=metadata, + ) metadata = dict(message.metadata) path = str(destination) metadata["has_media"] = True @@ -570,6 +597,13 @@ async def _download_inbound_media( if not isinstance(file_path, str): msg = "Telegram getFile response missing file_path" raise TelegramError(msg) + file_size = result.get("file_size") if isinstance(result, dict) else None + if isinstance(file_size, int) and file_size > self.config.max_media_bytes: + msg = ( + "Telegram media is too large: " + f"{file_size} bytes exceeds {self.config.max_media_bytes}" + ) + raise ChannelMediaError(msg) if self.config.inbound_media_dir is None: msg = "Telegram inbound media directory is not configured" raise TelegramError(msg) @@ -580,7 +614,13 @@ async def _download_inbound_media( suffix=suffix, ) download_url = f"{self.config.api_base}/file/bot{self.config.bot_token}/{file_path}" - await asyncio.to_thread(_download_file, download_url, destination, self.timeout) + await asyncio.to_thread( + _download_file, + download_url, + destination, + self.timeout, + self.config.max_media_bytes, + ) return destination @property @@ -990,13 +1030,17 @@ def _largest_photo_file_id(photo_sizes: object) -> str | None: return file_id if isinstance(file_id, str) else None -def _download_file(url: str, destination: Path, timeout: float) -> None: +def _download_file(url: str, destination: Path, timeout: float, max_bytes: int) -> None: """Download a file from a URL to a local path. Args: url: Source URL. destination: Destination file path. timeout: Download timeout in seconds. + max_bytes: Maximum bytes to write before aborting. + + Raises: + ChannelMediaError: If the remote file exceeds `max_bytes`. """ destination.parent.mkdir(mode=0o700, parents=True, exist_ok=True) request = urllib.request.Request(url) # noqa: S310 # URL constructed from Bot API config. @@ -1004,7 +1048,26 @@ def _download_file(url: str, destination: Path, timeout: float) -> None: request, timeout=timeout, ) as response: - destination.write_bytes(response.read()) + length = response.headers.get("content-length") + if length is not None: + try: + expected = int(length) + except ValueError: + expected = None + if expected is not None and expected > max_bytes: + msg = f"media file is too large: {expected} bytes exceeds {max_bytes}" + raise ChannelMediaError(msg) + + total = 0 + with destination.open("wb") as file: + while chunk := response.read(64 * 1024): + total += len(chunk) + if total > max_bytes: + file.close() + destination.unlink(missing_ok=True) + msg = f"media file is too large: {total} bytes exceeds {max_bytes}" + raise ChannelMediaError(msg) + file.write(chunk) destination.chmod(0o600) diff --git a/libs/talon/deepagents_talon/channels/whatsapp.py b/libs/talon/deepagents_talon/channels/whatsapp.py index b3857fb19b7..65a3751e92c 100644 --- a/libs/talon/deepagents_talon/channels/whatsapp.py +++ b/libs/talon/deepagents_talon/channels/whatsapp.py @@ -21,17 +21,21 @@ from typing import TYPE_CHECKING, cast from deepagents_talon.channels.base import ( + DEFAULT_MAX_MEDIA_BYTES, MAX_TEXT_CHARS, ChannelExposure, + ChannelMediaError, ExposureMode, chunk_text, format_markdown_for_channel, + max_media_bytes_from_env, validate_media, + validate_media_size, ) from deepagents_talon.interfaces import ChannelMedia, ChannelMessage, ChannelStatus, MessageHandler if TYPE_CHECKING: - from collections.abc import Mapping + from collections.abc import Mapping, Sequence from deepagents_talon.config import TalonConfig @@ -72,6 +76,8 @@ class WhatsAppChannelConfig: chrome_path: Optional Chrome or Chromium executable path for Puppeteer. web_version_cache_url: Optional pinned WhatsApp Web HTML cache URL. bridge_token: Bearer token shared with the loopback bridge process. + max_media_bytes: Maximum media bytes allowed for inbound bridge downloads + and outbound local files. poll_interval_seconds: Interval for draining inbound bridge messages. health_interval_seconds: Interval for bridge health checks. request_timeout_seconds: Per-request timeout for loopback bridge calls. @@ -91,6 +97,7 @@ class WhatsAppChannelConfig: default_factory=lambda: secrets.token_hex(DEFAULT_BRIDGE_TOKEN_BYTES), repr=False, ) + max_media_bytes: int = DEFAULT_MAX_MEDIA_BYTES poll_interval_seconds: float = DEFAULT_POLL_INTERVAL_SECONDS health_interval_seconds: float = DEFAULT_HEALTH_INTERVAL_SECONDS request_timeout_seconds: float = DEFAULT_REQUEST_TIMEOUT_SECONDS @@ -139,6 +146,7 @@ def from_talon_config(cls, config: TalonConfig) -> WhatsAppChannelConfig: web_version_cache_url=env.get("DEEPAGENTS_TALON_WHATSAPP_WEB_VERSION_CACHE_URL"), bridge_token=env.get("DEEPAGENTS_TALON_WHATSAPP_BRIDGE_TOKEN") or secrets.token_hex(DEFAULT_BRIDGE_TOKEN_BYTES), + max_media_bytes=max_media_bytes_from_env(env), poll_interval_seconds=_parse_float( env.get("DEEPAGENTS_TALON_WHATSAPP_POLL_SECONDS"), DEFAULT_POLL_INTERVAL_SECONDS, @@ -300,7 +308,11 @@ async def send_media(self, conversation_id: str, media: ChannelMedia) -> None: conversation_id: WhatsApp chat id. media: Media payload to send. """ - checked = validate_media(media, root=self.config.outbound_media_dir) + checked = validate_media( + media, + root=self.config.outbound_media_dir, + max_bytes=self.config.max_media_bytes, + ) staged = await asyncio.to_thread(_stage_bridge_media, checked.path, self.config) payload: dict[str, object] = { "chat_id": conversation_id, @@ -360,6 +372,7 @@ async def _start_bridge(self) -> None: "WHATSAPP_BOT_HEADER": self.config.bot_header, "WHATSAPP_BRIDGE_TOKEN": self.config.bridge_token, "WHATSAPP_MEDIA_DIR": str(_bridge_media_dir(self.config)), + "WHATSAPP_MAX_MEDIA_BYTES": str(self.config.max_media_bytes), } if self.config.chrome_path: env["WHATSAPP_CHROME_PATH"] = self.config.chrome_path @@ -407,7 +420,11 @@ async def _poll_messages(self) -> None: payload = await self._transport.get("/messages") for message in _parse_messages(payload): if self.config.exposure.allows(message): - await self._dispatch(message) + checked = _enforce_inbound_media_cap( + message, + max_bytes=self.config.max_media_bytes, + ) + await self._dispatch(checked) else: logger.debug( "Dropping WhatsApp message %s from %s due to exposure policy", @@ -599,6 +616,90 @@ def _parse_message(payload: object) -> ChannelMessage: ) +def _enforce_inbound_media_cap(message: ChannelMessage, *, max_bytes: int) -> ChannelMessage: + media_paths = message.metadata.get("media_paths") + if not isinstance(media_paths, list) or not media_paths: + return message + + mime_types = message.metadata.get("media_mime_types") + kept, kept_mime_types, changed = _filter_inbound_media( + message, + media_paths=media_paths, + mime_types=mime_types if isinstance(mime_types, list) else [], + max_bytes=max_bytes, + ) + if not changed: + return message + return _with_inbound_media_paths( + message, + media_paths=kept, + mime_types=kept_mime_types, + max_bytes=max_bytes, + ) + + +def _filter_inbound_media( + message: ChannelMessage, + *, + media_paths: Sequence[object], + mime_types: Sequence[object], + max_bytes: int, +) -> tuple[list[str], list[str], bool]: + kept: list[str] = [] + kept_mime_types: list[str] = [] + changed = False + for index, raw_path in enumerate(media_paths): + if not isinstance(raw_path, str): + changed = True + continue + try: + validate_media_size(Path(raw_path), max_bytes=max_bytes) + except FileNotFoundError: + kept.append(raw_path) + except ChannelMediaError as error: + logger.warning( + "Skipping WhatsApp inbound media for message %s: %s", + message.message_id, + error, + ) + changed = True + continue + else: + kept.append(raw_path) + if index < len(mime_types): + mime_type = mime_types[index] + if isinstance(mime_type, str): + kept_mime_types.append(mime_type) + return kept, kept_mime_types, changed + + +def _with_inbound_media_paths( + message: ChannelMessage, + *, + media_paths: list[str], + mime_types: list[str], + max_bytes: int, +) -> ChannelMessage: + metadata = dict(message.metadata) + metadata["media_paths"] = media_paths + metadata["media_path"] = media_paths[0] if media_paths else None + metadata["media_mime_types"] = mime_types + metadata["media_types"] = mime_types + metadata["voice_path"] = ( + media_paths[0] if media_paths and metadata.get("media_type") == "voice" else None + ) + metadata["has_media"] = bool(media_paths) + if not media_paths: + metadata["media_error"] = f"all media files exceeded {max_bytes} bytes" + return ChannelMessage( + conversation_id=message.conversation_id, + text=message.text, + sender_id=message.sender_id, + message_id=message.message_id, + metadata=metadata, + ) + + def _parse_status(payload: object) -> ChannelStatus: if not isinstance(payload, dict): msg = "WhatsApp bridge /health response must be an object" diff --git a/libs/talon/deepagents_talon/channels/whatsapp_bridge/bridge.js b/libs/talon/deepagents_talon/channels/whatsapp_bridge/bridge.js index 187774149eb..793cad0c97a 100644 --- a/libs/talon/deepagents_talon/channels/whatsapp_bridge/bridge.js +++ b/libs/talon/deepagents_talon/channels/whatsapp_bridge/bridge.js @@ -12,8 +12,16 @@ const sessionDir = path.resolve(process.env.WHATSAPP_SESSION_DIR || path.join(pr const mediaDir = path.resolve(process.env.WHATSAPP_MEDIA_DIR || path.join(sessionDir, "..", "media")); const botHeader = process.env.WHATSAPP_BOT_HEADER || "deepagents bot"; const bridgeToken = process.env.WHATSAPP_BRIDGE_TOKEN || ""; -const rawMaxMediaBytes = Number(process.env.WHATSAPP_MAX_MEDIA_BYTES || String(64 * 1024 * 1024)); -const maxMediaBytes = Number.isFinite(rawMaxMediaBytes) && rawMaxMediaBytes > 0 ? rawMaxMediaBytes : 64 * 1024 * 1024; +const defaultMaxMediaBytes = 1024 * 1024 * 1024; +const rawMaxMediaBytes = Number( + process.env.DEEPAGENTS_TALON_MAX_MEDIA_BYTES || + process.env.WHATSAPP_MAX_MEDIA_BYTES || + String(defaultMaxMediaBytes), +); +const maxMediaBytes = + Number.isFinite(rawMaxMediaBytes) && rawMaxMediaBytes > 0 + ? rawMaxMediaBytes + : defaultMaxMediaBytes; const webVersionCacheUrl = process.env.WHATSAPP_WEB_VERSION_CACHE_URL || "https://raw.githubusercontent.com/wppconnect-team/wa-version/main/html/2.3000.1026029003.html"; diff --git a/libs/talon/tests/channels/test_base.py b/libs/talon/tests/channels/test_base.py index 7b1f66acc49..0a0017263d9 100644 --- a/libs/talon/tests/channels/test_base.py +++ b/libs/talon/tests/channels/test_base.py @@ -5,11 +5,13 @@ import pytest from deepagents_talon.channels.base import ( + DEFAULT_MAX_MEDIA_BYTES, ChannelExposure, ChannelMediaError, ExposureMode, chunk_text, format_markdown_for_channel, + max_media_bytes_from_env, validate_media, ) from deepagents_talon.interfaces import ChannelMedia, ChannelMessage @@ -82,6 +84,14 @@ def test_validate_media_accepts_relative_path_under_root(tmp_path: Path) -> None assert media == ChannelMedia(path=path.resolve(), media_type="image") +def test_validate_media_rejects_configured_global_cap(tmp_path: Path) -> None: + path = tmp_path / "image.png" + path.write_bytes(b"abcd") + + with pytest.raises(ChannelMediaError, match="exceeds 3"): + validate_media(ChannelMedia(path=path, media_type="image"), max_bytes=3) + + def test_validate_media_rejects_path_outside_root(tmp_path: Path) -> None: root = tmp_path / "workspace" root.mkdir() @@ -98,3 +108,16 @@ def test_validate_media_rejects_type_mismatch(tmp_path: Path) -> None: with pytest.raises(ChannelMediaError, match="does not match"): validate_media(ChannelMedia(path=path, media_type="video")) + + +def test_max_media_bytes_from_env_defaults_to_one_gb() -> None: + assert max_media_bytes_from_env({}) == DEFAULT_MAX_MEDIA_BYTES + + +def test_max_media_bytes_from_env_accepts_positive_integer() -> None: + assert max_media_bytes_from_env({"DEEPAGENTS_TALON_MAX_MEDIA_BYTES": "123"}) == 123 + + +def test_max_media_bytes_from_env_rejects_invalid_values() -> None: + with pytest.raises(ValueError, match="positive integer"): + max_media_bytes_from_env({"DEEPAGENTS_TALON_MAX_MEDIA_BYTES": "0"}) diff --git a/libs/talon/tests/channels/test_telegram.py b/libs/talon/tests/channels/test_telegram.py index 3107434a8ad..5898bf76a3c 100644 --- a/libs/talon/tests/channels/test_telegram.py +++ b/libs/talon/tests/channels/test_telegram.py @@ -4,12 +4,13 @@ import json import os from pathlib import Path -from typing import cast +from typing import Self, cast import pytest import deepagents_talon.channels.telegram as telegram_module from deepagents_talon.channels.base import ( + DEFAULT_MAX_MEDIA_BYTES, ChannelExposure, ChannelMediaError, ExposureMode, @@ -21,6 +22,7 @@ TelegramChannelConfig, TelegramError, TelegramTransport, + _download_file, _encode_multipart_form, _escape_markdown_v2, _load_offset, @@ -179,7 +181,12 @@ def _make_config( def _stub_download(monkeypatch: pytest.MonkeyPatch) -> None: - def download(url: str, destination: Path, timeout: float) -> None: # noqa: ARG001 + def download( + _url: str, + destination: Path, + _timeout: float, + _max_bytes: int, + ) -> None: destination.parent.mkdir(mode=0o700, parents=True, exist_ok=True) destination.write_bytes(b"media-bytes") destination.chmod(0o600) @@ -218,6 +225,23 @@ def test_config_from_talon_env_maps_telegram_values(tmp_path: Path) -> None: assert telegram.allowed_user_ids == frozenset({"777", "888"}) assert telegram.poll_timeout_seconds == 45.0 assert telegram.poll_interval_seconds == 2.0 + assert telegram.max_media_bytes == DEFAULT_MAX_MEDIA_BYTES + + +def test_config_from_talon_env_maps_max_media_bytes(tmp_path: Path) -> None: + config = TalonConfig.from_env( + { + "AGENT_ASSISTANT_ID": "assistant", + "DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN": "secret-token", + "DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID": "999", + "DEEPAGENTS_TALON_MAX_MEDIA_BYTES": "12345", + }, + base_home=tmp_path, + ) + + telegram = TelegramChannelConfig.from_talon_config(config) + + assert telegram.max_media_bytes == 12345 def test_config_accepts_telegram_bot_token_alias(tmp_path: Path) -> None: @@ -884,6 +908,97 @@ async def record(message: ChannelMessage) -> None: ] +async def test_channel_skips_oversized_inbound_media_from_get_file( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + class OversizedGetFileTransport(RecordingTransport): + async def call(self, method: str, **params: object) -> object: + if method == "getFile": + self.calls.append((method, dict(params))) + return { + "ok": True, + "result": { + "file_id": params.get("file_id"), + "file_path": "documents/report.pdf", + "file_size": 11, + }, + } + return await super().call(method, **params) + + _stub_download(monkeypatch) + transport = OversizedGetFileTransport( + updates=[ + _make_update( + update_id=10, + chat_id=111, + sender_id=111, + text="oversized", + document={"file_id": "doc123", "file_name": "report.pdf"}, + ), + ], + ) + config = TelegramChannelConfig( + bot_token="test-token", # noqa: S106 # inert test token + session_dir=tmp_path / "telegram", + inbound_media_dir=tmp_path / "telegram" / "media", + outbound_media_dir=tmp_path, + exposure=ChannelExposure(operator_id="111"), + poll_interval_seconds=60, + poll_timeout_seconds=1, + max_media_bytes=10, + ) + channel = TelegramChannel(config, transport=cast("TelegramTransport", transport)) + received: list[ChannelMessage] = [] + + async def record(message: ChannelMessage) -> None: + received.append(message) + + channel.set_message_handler(record) + + await channel.start() + await _wait_for_received(received, 1) + await channel.stop() + + assert received[0].text == "oversized" + assert received[0].metadata["has_media"] is False + assert "media_error" in received[0].metadata + assert "media_paths" not in received[0].metadata + assert _load_offset(config.offset_file) == 11 + + +def test_download_file_aborts_when_stream_exceeds_cap( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + class ChunkedResponse: + def __init__(self) -> None: + self.headers: dict[str, str] = {} + self.chunks = [b"abc", b"def"] + + def __enter__(self) -> Self: + return self + + def __exit__(self, *args: object) -> None: + return None + + def read(self, size: int = -1) -> bytes: # noqa: ARG002 # urllib-compatible fake + if not self.chunks: + return b"" + return self.chunks.pop(0) + + def fake_urlopen(request: object, *, timeout: float) -> ChunkedResponse: # noqa: ARG001 + return ChunkedResponse() + + destination = tmp_path / "media.bin" + monkeypatch.setattr("urllib.request.urlopen", fake_urlopen) + + with pytest.raises(ChannelMediaError, match="exceeds 5"): + _download_file("https://example.com/file", destination, 1, 5) + + assert not destination.exists() + + # --- Status tests --- diff --git a/libs/talon/tests/channels/test_whatsapp.py b/libs/talon/tests/channels/test_whatsapp.py index 8b279e6d90c..6226eec1c76 100644 --- a/libs/talon/tests/channels/test_whatsapp.py +++ b/libs/talon/tests/channels/test_whatsapp.py @@ -8,7 +8,12 @@ import pytest -from deepagents_talon.channels.base import ChannelExposure, ChannelMediaError, ExposureMode +from deepagents_talon.channels.base import ( + DEFAULT_MAX_MEDIA_BYTES, + ChannelExposure, + ChannelMediaError, + ExposureMode, +) from deepagents_talon.channels.whatsapp import ( BridgeTransport, WhatsAppBridgeError, @@ -86,6 +91,7 @@ def test_config_from_talon_env_maps_exposure( assert whatsapp.session_dir == tmp_path / "assistant" / "channels" / "whatsapp" assert whatsapp.inbound_media_dir == tmp_path / "assistant" / "media" / "inbound" / "whatsapp" assert whatsapp.outbound_media_dir == tmp_path + assert whatsapp.max_media_bytes == DEFAULT_MAX_MEDIA_BYTES assert whatsapp.exposure == ChannelExposure( mode=ExposureMode.ALLOWLIST, operator_id="operator", @@ -95,6 +101,20 @@ def test_config_from_talon_env_maps_exposure( assert whatsapp.bot_header == "test bot" +def test_config_from_talon_env_maps_max_media_bytes(tmp_path: Path) -> None: + config = TalonConfig.from_env( + { + "AGENT_ASSISTANT_ID": "assistant", + "DEEPAGENTS_TALON_MAX_MEDIA_BYTES": "12345", + }, + base_home=tmp_path, + ) + + whatsapp = WhatsAppChannelConfig.from_talon_config(config) + + assert whatsapp.max_media_bytes == 12345 + + def test_config_from_talon_env_accepts_explicit_bridge_token(tmp_path: Path) -> None: config = TalonConfig.from_env( { @@ -291,6 +311,52 @@ async def record(message: ChannelMessage) -> None: assert received[0].metadata["voice_path"] == str(media) +async def test_channel_filters_oversized_inbound_media_payload(tmp_path: Path) -> None: + media = tmp_path / "voice.ogg" + media.write_bytes(b"voice") + transport = RecordingTransport( + messages=[ + { + "body": "oversized", + "chatId": "chat@lid", + "senderId": "operator", + "messageId": "message-1", + "messageType": "ptt", + "mediaType": "voice", + "mediaPaths": [str(media)], + "mediaMimeTypes": ["audio/ogg"], + "fromSelf": True, + }, + ], + ) + channel = WhatsAppChannel( + WhatsAppChannelConfig( + session_dir=tmp_path, + max_media_bytes=1, + poll_interval_seconds=60, + health_interval_seconds=60, + ), + transport=cast("BridgeTransport", transport), + ) + received: list[ChannelMessage] = [] + + async def record(message: ChannelMessage) -> None: + received.append(message) + + channel.set_message_handler(record) + + await channel.start() + await asyncio.sleep(0) + await channel.stop() + + assert received[0].text == "oversized" + assert received[0].metadata["has_media"] is False + assert received[0].metadata["media_paths"] == [] + assert received[0].metadata["media_path"] is None + assert received[0].metadata["voice_path"] is None + assert "media_error" in received[0].metadata + + async def test_channel_normalizes_ptt_payload_as_voice(tmp_path: Path) -> None: media = tmp_path / "voice.ogg" media.write_bytes(b"voice") @@ -448,6 +514,47 @@ async def test_channel_rejects_media_outside_configured_outbound_root(tmp_path: assert transport.posts == [] +async def test_channel_forwards_max_media_bytes_to_bridge( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + captured: dict[str, object] = {} + + class FakeProcess: + stdout = None + stderr = None + returncode = None + + async def fake_create_subprocess_exec( + *command: str, + env: dict[str, str], + stdout: object, + stderr: object, + ) -> FakeProcess: + captured["command"] = command + captured["env"] = env + captured["stdout"] = stdout + captured["stderr"] = stderr + return FakeProcess() + + async def fake_wait_for_bridge() -> None: + return None + + monkeypatch.setattr("asyncio.create_subprocess_exec", fake_create_subprocess_exec) + config = WhatsAppChannelConfig( + session_dir=tmp_path, + bridge_command=("node", "bridge.js"), + max_media_bytes=12345, + ) + channel = WhatsAppChannel(config) + monkeypatch.setattr(channel, "_wait_for_bridge", fake_wait_for_bridge) + + await channel._start_bridge() + + env = cast("dict[str, str]", captured["env"]) + assert env["WHATSAPP_MAX_MEDIA_BYTES"] == "12345" + + async def test_channel_waits_for_bridge_health_before_polling(tmp_path: Path) -> None: transport = DelayedHealthTransport() channel = WhatsAppChannel( From 0b6fe25bf41551d278f1da0d73f31a69e7b2191c Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sat, 20 Jun 2026 11:09:50 -0700 Subject: [PATCH 10/48] fix(talon): clamp WhatsApp media cap --- libs/talon/README.md | 4 +- .../deepagents_talon/channels/whatsapp.py | 14 +++++-- .../channels/whatsapp_bridge/bridge.js | 38 ++++++++++++++++--- libs/talon/tests/channels/test_whatsapp.py | 18 ++++++++- 4 files changed, 61 insertions(+), 13 deletions(-) diff --git a/libs/talon/README.md b/libs/talon/README.md index cd2c47109b1..ba0d9925d4b 100644 --- a/libs/talon/README.md +++ b/libs/talon/README.md @@ -67,7 +67,7 @@ AGENT_MODEL=: \ uv run deepagents-talon --whatsapp ``` -The bridge prints a QR code during pairing. By default, inbound exposure is `self`, so only messages from the paired account trigger the agent. Configure `DEEPAGENTS_TALON_WHATSAPP_EXPOSURE=allowlist` with `DEEPAGENTS_TALON_WHATSAPP_ALLOWLIST_CHATS` or `DEEPAGENTS_TALON_WHATSAPP_MENTION_PATTERNS` to allow specific chats. Outbound WhatsApp messages include a `deepagents bot` header by default so self-message conversations clearly distinguish agent replies from operator messages. Set `DEEPAGENTS_TALON_WHATSAPP_BOT_HEADER` to customize that label. Markdown image/video references in assistant replies may attach files only when they are relative paths inside `DEEPAGENTS_TALON_OUTBOUND_MEDIA_DIR`, or inside `DEEPAGENTS_TALON_WORKSPACE` when no outbound media directory is configured. `DEEPAGENTS_TALON_MAX_MEDIA_BYTES` caps inbound and outbound channel media across providers and defaults to `1073741824` (1 GiB). +The bridge prints a QR code during pairing. By default, inbound exposure is `self`, so only messages from the paired account trigger the agent. Configure `DEEPAGENTS_TALON_WHATSAPP_EXPOSURE=allowlist` with `DEEPAGENTS_TALON_WHATSAPP_ALLOWLIST_CHATS` or `DEEPAGENTS_TALON_WHATSAPP_MENTION_PATTERNS` to allow specific chats. Outbound WhatsApp messages include a `deepagents bot` header by default so self-message conversations clearly distinguish agent replies from operator messages. Set `DEEPAGENTS_TALON_WHATSAPP_BOT_HEADER` to customize that label. Markdown image/video references in assistant replies may attach files only when they are relative paths inside `DEEPAGENTS_TALON_OUTBOUND_MEDIA_DIR`, or inside `DEEPAGENTS_TALON_WORKSPACE` when no outbound media directory is configured. `DEEPAGENTS_TALON_MAX_MEDIA_BYTES` caps inbound and outbound channel media across providers and defaults to `1073741824` (1 GiB), but WhatsApp is clamped to `67108864` (64 MiB) because the bridge library materializes downloads in memory before writing them. Inbound voice transcription is opt-in: @@ -177,7 +177,7 @@ Sensitive local state is stored under `~/.deepagents//` by default - `cron/jobs.json` stores cron prompts, origin conversation ids, message ids, run status, and errors. Active jobs are retained while enabled. Completed jobs are deleted on startup after `DEEPAGENTS_TALON_CRON_RETENTION_DAYS`, default `30`. - `channels/whatsapp/` stores WhatsApp `LocalAuth` credentials and Chromium profile state. These credentials are retained until the operator deletes the directory, because automatic deletion would silently unpair the channel. -- `media/inbound/` is reserved for downloaded inbound media. Files older than `DEEPAGENTS_TALON_INBOUND_MEDIA_RETENTION_HOURS`, default `24`, are deleted on startup. Inbound and outbound channel media are capped by `DEEPAGENTS_TALON_MAX_MEDIA_BYTES`, default `1073741824` (1 GiB). The WhatsApp bridge stores downloaded inbound media under the assistant's inbound media directory and passes local paths plus MIME metadata to the host. +- `media/inbound/` is reserved for downloaded inbound media. Files older than `DEEPAGENTS_TALON_INBOUND_MEDIA_RETENTION_HOURS`, default `24`, are deleted on startup. Inbound and outbound channel media are capped by `DEEPAGENTS_TALON_MAX_MEDIA_BYTES`, default `1073741824` (1 GiB); WhatsApp is further clamped to `67108864` (64 MiB). The WhatsApp bridge stores downloaded inbound media under the assistant's inbound media directory and passes local paths plus MIME metadata to the host. Conversation persistence is intentionally not durable yet. Runtime conversation state is in-memory unless a future backend explicitly adds thread persistence. diff --git a/libs/talon/deepagents_talon/channels/whatsapp.py b/libs/talon/deepagents_talon/channels/whatsapp.py index 65a3751e92c..fdd30886573 100644 --- a/libs/talon/deepagents_talon/channels/whatsapp.py +++ b/libs/talon/deepagents_talon/channels/whatsapp.py @@ -21,7 +21,6 @@ from typing import TYPE_CHECKING, cast from deepagents_talon.channels.base import ( - DEFAULT_MAX_MEDIA_BYTES, MAX_TEXT_CHARS, ChannelExposure, ChannelMediaError, @@ -49,6 +48,7 @@ DEFAULT_BRIDGE_START_TIMEOUT_SECONDS = 10.0 DEFAULT_BOT_HEADER = "deepagents bot" DEFAULT_BRIDGE_TOKEN_BYTES = 32 +DEFAULT_WHATSAPP_MAX_MEDIA_BYTES = 64 * 1024 * 1024 _FAILED_HEALTH_RESTART_THRESHOLD = 3 OPEN_EXPOSURE_ACK_ENV = "DEEPAGENTS_TALON_WHATSAPP_OPEN_ACK" OPEN_EXPOSURE_ACK_VALUE = "allow-arbitrary-senders" @@ -77,7 +77,9 @@ class WhatsAppChannelConfig: web_version_cache_url: Optional pinned WhatsApp Web HTML cache URL. bridge_token: Bearer token shared with the loopback bridge process. max_media_bytes: Maximum media bytes allowed for inbound bridge downloads - and outbound local files. + and outbound local files. WhatsApp stores downloaded media in memory + before the bridge can write it, so this defaults lower than the + cross-channel cap. poll_interval_seconds: Interval for draining inbound bridge messages. health_interval_seconds: Interval for bridge health checks. request_timeout_seconds: Per-request timeout for loopback bridge calls. @@ -97,7 +99,7 @@ class WhatsAppChannelConfig: default_factory=lambda: secrets.token_hex(DEFAULT_BRIDGE_TOKEN_BYTES), repr=False, ) - max_media_bytes: int = DEFAULT_MAX_MEDIA_BYTES + max_media_bytes: int = DEFAULT_WHATSAPP_MAX_MEDIA_BYTES poll_interval_seconds: float = DEFAULT_POLL_INTERVAL_SECONDS health_interval_seconds: float = DEFAULT_HEALTH_INTERVAL_SECONDS request_timeout_seconds: float = DEFAULT_REQUEST_TIMEOUT_SECONDS @@ -146,7 +148,7 @@ def from_talon_config(cls, config: TalonConfig) -> WhatsAppChannelConfig: web_version_cache_url=env.get("DEEPAGENTS_TALON_WHATSAPP_WEB_VERSION_CACHE_URL"), bridge_token=env.get("DEEPAGENTS_TALON_WHATSAPP_BRIDGE_TOKEN") or secrets.token_hex(DEFAULT_BRIDGE_TOKEN_BYTES), - max_media_bytes=max_media_bytes_from_env(env), + max_media_bytes=_whatsapp_max_media_bytes_from_env(env), poll_interval_seconds=_parse_float( env.get("DEEPAGENTS_TALON_WHATSAPP_POLL_SECONDS"), DEFAULT_POLL_INTERVAL_SECONDS, @@ -539,6 +541,10 @@ def _bridge_media_dir(config: WhatsAppChannelConfig) -> Path: return config.inbound_media_dir or config.session_dir.parent / "media" +def _whatsapp_max_media_bytes_from_env(env: Mapping[str, str]) -> int: + return min(max_media_bytes_from_env(env), DEFAULT_WHATSAPP_MAX_MEDIA_BYTES) + + def _stage_bridge_media(path: Path, config: WhatsAppChannelConfig) -> Path: media_dir = _bridge_media_dir(config).expanduser().resolve() source = path.expanduser().resolve() diff --git a/libs/talon/deepagents_talon/channels/whatsapp_bridge/bridge.js b/libs/talon/deepagents_talon/channels/whatsapp_bridge/bridge.js index 793cad0c97a..bcfae819754 100644 --- a/libs/talon/deepagents_talon/channels/whatsapp_bridge/bridge.js +++ b/libs/talon/deepagents_talon/channels/whatsapp_bridge/bridge.js @@ -12,16 +12,16 @@ const sessionDir = path.resolve(process.env.WHATSAPP_SESSION_DIR || path.join(pr const mediaDir = path.resolve(process.env.WHATSAPP_MEDIA_DIR || path.join(sessionDir, "..", "media")); const botHeader = process.env.WHATSAPP_BOT_HEADER || "deepagents bot"; const bridgeToken = process.env.WHATSAPP_BRIDGE_TOKEN || ""; -const defaultMaxMediaBytes = 1024 * 1024 * 1024; +const defaultWhatsAppMaxMediaBytes = 64 * 1024 * 1024; const rawMaxMediaBytes = Number( process.env.DEEPAGENTS_TALON_MAX_MEDIA_BYTES || process.env.WHATSAPP_MAX_MEDIA_BYTES || - String(defaultMaxMediaBytes), + String(defaultWhatsAppMaxMediaBytes), ); const maxMediaBytes = Number.isFinite(rawMaxMediaBytes) && rawMaxMediaBytes > 0 - ? rawMaxMediaBytes - : defaultMaxMediaBytes; + ? Math.min(rawMaxMediaBytes, defaultWhatsAppMaxMediaBytes) + : defaultWhatsAppMaxMediaBytes; const webVersionCacheUrl = process.env.WHATSAPP_WEB_VERSION_CACHE_URL || "https://raw.githubusercontent.com/wppconnect-team/wa-version/main/html/2.3000.1026029003.html"; @@ -284,11 +284,18 @@ async function downloadMessageMedia(message) { return []; } try { + const messageId = serializedId(message.id) || String(Date.now()); + const expectedSize = messageMediaSize(message); + if (expectedSize !== null && expectedSize > maxMediaBytes) { + console.log( + `[bridge] Skipping oversized media ${messageId}: ${expectedSize} bytes exceeds ${maxMediaBytes}`, + ); + return []; + } const media = await message.downloadMedia(); if (!media || !media.data) { return []; } - const messageId = serializedId(message.id) || String(Date.now()); const extension = mediaExtension(media.mimetype, message.type); const fileName = `${Date.now()}_${messageId.replace(/[^A-Za-z0-9]/g, "_")}.${extension}`; const filePath = path.join(mediaDir, fileName); @@ -339,6 +346,27 @@ function messageMimeType(message, media) { return String(message.mimetype || data.mimetype || data.mimetypeOverride || "").toLowerCase(); } +function messageMediaSize(message) { + const data = message && message._data ? message._data : {}; + const candidates = [ + message.size, + message.fileSize, + message.filesize, + message.mediaSize, + data.size, + data.fileSize, + data.filesize, + data.mediaSize, + ]; + for (const candidate of candidates) { + const parsed = Number(candidate); + if (Number.isFinite(parsed) && parsed >= 0) { + return parsed; + } + } + return null; +} + function mediaExtension(mimeType, messageType) { const raw = String(mimeType || "").split(";", 1)[0]; const subtype = raw.includes("/") ? raw.split("/")[1] : ""; diff --git a/libs/talon/tests/channels/test_whatsapp.py b/libs/talon/tests/channels/test_whatsapp.py index 6226eec1c76..d80aa9e31e1 100644 --- a/libs/talon/tests/channels/test_whatsapp.py +++ b/libs/talon/tests/channels/test_whatsapp.py @@ -9,12 +9,12 @@ import pytest from deepagents_talon.channels.base import ( - DEFAULT_MAX_MEDIA_BYTES, ChannelExposure, ChannelMediaError, ExposureMode, ) from deepagents_talon.channels.whatsapp import ( + DEFAULT_WHATSAPP_MAX_MEDIA_BYTES, BridgeTransport, WhatsAppBridgeError, WhatsAppChannel, @@ -91,7 +91,7 @@ def test_config_from_talon_env_maps_exposure( assert whatsapp.session_dir == tmp_path / "assistant" / "channels" / "whatsapp" assert whatsapp.inbound_media_dir == tmp_path / "assistant" / "media" / "inbound" / "whatsapp" assert whatsapp.outbound_media_dir == tmp_path - assert whatsapp.max_media_bytes == DEFAULT_MAX_MEDIA_BYTES + assert whatsapp.max_media_bytes == DEFAULT_WHATSAPP_MAX_MEDIA_BYTES assert whatsapp.exposure == ChannelExposure( mode=ExposureMode.ALLOWLIST, operator_id="operator", @@ -115,6 +115,20 @@ def test_config_from_talon_env_maps_max_media_bytes(tmp_path: Path) -> None: assert whatsapp.max_media_bytes == 12345 +def test_config_from_talon_env_clamps_large_max_media_bytes(tmp_path: Path) -> None: + config = TalonConfig.from_env( + { + "AGENT_ASSISTANT_ID": "assistant", + "DEEPAGENTS_TALON_MAX_MEDIA_BYTES": str(DEFAULT_WHATSAPP_MAX_MEDIA_BYTES + 1), + }, + base_home=tmp_path, + ) + + whatsapp = WhatsAppChannelConfig.from_talon_config(config) + + assert whatsapp.max_media_bytes == DEFAULT_WHATSAPP_MAX_MEDIA_BYTES + + def test_config_from_talon_env_accepts_explicit_bridge_token(tmp_path: Path) -> None: config = TalonConfig.from_env( { From 7ea89d8684b503de219d24ba22b115e17e72dc9a Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sat, 20 Jun 2026 11:27:37 -0700 Subject: [PATCH 11/48] refactor(talon): share channel exposure and media helpers --- libs/talon/deepagents_talon/channels/base.py | 259 +++++++++++++++++- .../deepagents_talon/channels/whatsapp.py | 171 +++--------- libs/talon/tests/channels/test_whatsapp.py | 7 +- 3 files changed, 302 insertions(+), 135 deletions(-) diff --git a/libs/talon/deepagents_talon/channels/base.py b/libs/talon/deepagents_talon/channels/base.py index 5273ad16a3d..a3d0791c2be 100644 --- a/libs/talon/deepagents_talon/channels/base.py +++ b/libs/talon/deepagents_talon/channels/base.py @@ -10,20 +10,21 @@ import re from dataclasses import dataclass, field from enum import StrEnum +from pathlib import Path from typing import TYPE_CHECKING from deepagents_talon.interfaces import ChannelMedia, ChannelMessage from deepagents_talon.media import resolve_bounded_media_path if TYPE_CHECKING: - from collections.abc import Mapping - from pathlib import Path + from collections.abc import Mapping, Sequence MAX_TEXT_CHARS = 4096 MAX_IMAGE_BYTES = 16 * 1024 * 1024 MAX_VIDEO_BYTES = 64 * 1024 * 1024 DEFAULT_MAX_MEDIA_BYTES = 1024 * 1024 * 1024 MAX_MEDIA_BYTES_ENV = "DEEPAGENTS_TALON_MAX_MEDIA_BYTES" +OPEN_EXPOSURE_ACK_VALUE = "allow-arbitrary-senders" _LINK_PATTERN = re.compile(r"\[([^\]]+)]\(([^)]+)\)") _HEADING_PATTERN = re.compile(r"^#{1,6}\s+", flags=re.MULTILINE) @@ -43,6 +44,48 @@ class ChannelMediaError(ValueError): """Raised when channel media cannot be handled safely.""" +@dataclass(frozen=True, slots=True) +class ChannelExposureEnv: + """Environment variable names used to build channel exposure policy. + + Args: + provider: Human-readable provider name used in error messages. + exposure: Environment variable containing the exposure mode. + allowlist_chats: Environment variable containing allowlisted chats. + mention_patterns: Environment variable containing allowlist text patterns. + operator_id: Environment variable containing the trusted operator id. + open_ack: Environment variable acknowledging open-exposure risk. + open_ack_value: Required acknowledgement value for open exposure. + require_self_operator: Whether `self` exposure requires an operator id. + """ + + provider: str + exposure: str + allowlist_chats: str + mention_patterns: str + operator_id: str + open_ack: str + open_ack_value: str = OPEN_EXPOSURE_ACK_VALUE + require_self_operator: bool = False + + +@dataclass(frozen=True, slots=True) +class FilteredMediaPaths: + """Inbound media paths retained after applying local size caps. + + Args: + paths: String paths that remain usable. + mime_types: MIME types aligned with `paths`. + changed: Whether any input path was dropped or ignored. + errors: Human-readable drop reasons for logs or metadata. + """ + + paths: tuple[str, ...] + mime_types: tuple[str, ...] + changed: bool + errors: tuple[str, ...] = () + + @dataclass(frozen=True, slots=True) class ChannelExposure: """Inbound exposure policy shared by channel adapters. @@ -122,6 +165,43 @@ def chunk_text(text: str, *, limit: int = MAX_TEXT_CHARS) -> list[str]: return chunks +def channel_exposure_from_env( + env: Mapping[str, str], + config: ChannelExposureEnv, +) -> ChannelExposure: + """Build shared channel exposure policy from provider-specific env names. + + Args: + env: Environment variable mapping. + config: Provider-specific exposure environment mapping. + + Returns: + Parsed exposure policy. + + Raises: + ValueError: If the exposure mode is invalid or risk acknowledgement is missing. + """ + mode = _exposure_mode( + env.get(config.exposure, ExposureMode.SELF.value), + provider=config.provider, + ) + operator_id = env.get(config.operator_id) or None + if mode == ExposureMode.SELF and config.require_self_operator and operator_id is None: + msg = ( + f"{config.provider} self exposure requires {config.operator_id}; " + f"set {config.exposure}=allowlist or open for other modes" + ) + raise ValueError(msg) + if mode == ExposureMode.OPEN: + _require_open_acknowledgement(env, config) + return ChannelExposure( + mode=mode, + operator_id=operator_id, + conversations=frozenset(split_csv(env.get(config.allowlist_chats, ""))), + mention_patterns=tuple(split_csv(env.get(config.mention_patterns, ""))), + ) + + def validate_media( media: ChannelMedia, *, @@ -163,6 +243,102 @@ def validate_media( return _validate_media_size(media, path=path, max_bytes=max_bytes) +def replace_message_metadata( + message: ChannelMessage, + metadata: Mapping[str, object], +) -> ChannelMessage: + """Return `message` with replaced metadata. + + Args: + message: Original channel message. + metadata: Replacement metadata. + + Returns: + Channel message with the same identity and text, plus new metadata. + """ + return ChannelMessage( + conversation_id=message.conversation_id, + text=message.text, + sender_id=message.sender_id, + message_id=message.message_id, + metadata=metadata, + ) + + +def message_with_media_paths( + message: ChannelMessage, + *, + media_paths: Sequence[str], + mime_types: Sequence[str] = (), +) -> ChannelMessage: + """Return `message` with normalized inbound-media path metadata. + + Args: + message: Original channel message. + media_paths: Local media paths associated with the message. + mime_types: MIME types aligned with `media_paths`. + + Returns: + Channel message with standard media path metadata. + """ + paths = list(media_paths) + types = list(mime_types) + metadata = dict(message.metadata) + metadata["media_paths"] = paths + metadata["media_path"] = paths[0] if paths else None + metadata["media_mime_types"] = types + metadata["media_types"] = types + metadata["voice_path"] = paths[0] if paths and metadata.get("media_type") == "voice" else None + metadata["has_media"] = bool(paths) + return replace_message_metadata(message, metadata) + + +def filter_capped_media_paths( + media_paths: Sequence[object], + mime_types: Sequence[object], + *, + max_bytes: int, +) -> FilteredMediaPaths: + """Filter inbound local media paths against a configured size cap. + + Args: + media_paths: Candidate local media paths from a channel payload. + mime_types: Candidate MIME types aligned with `media_paths`. + max_bytes: Maximum allowed file size. + + Returns: + Filter result containing kept paths and dropped-path reasons. + """ + kept: list[str] = [] + kept_mime_types: list[str] = [] + errors: list[str] = [] + changed = False + for index, raw_path in enumerate(media_paths): + if not isinstance(raw_path, str): + changed = True + continue + try: + validate_media_size(Path(raw_path), max_bytes=max_bytes) + except FileNotFoundError: + kept.append(raw_path) + except ChannelMediaError as error: + changed = True + errors.append(str(error)) + continue + else: + kept.append(raw_path) + if index < len(mime_types): + mime_type = mime_types[index] + if isinstance(mime_type, str): + kept_mime_types.append(mime_type) + return FilteredMediaPaths( + paths=tuple(kept), + mime_types=tuple(kept_mime_types), + changed=changed, + errors=tuple(errors), + ) + + def validate_media_size(path: Path, *, max_bytes: int) -> None: """Validate a local media file against the configured global cap. @@ -205,6 +381,62 @@ def max_media_bytes_from_env(env: Mapping[str, str]) -> int: return parsed +def parse_float(value: str | None, default: float) -> float: + """Parse an optional float value with a default. + + Args: + value: Raw environment value. + default: Value returned when `value` is missing. + + Returns: + Parsed float. + + Raises: + ValueError: If `value` is not a float. + """ + if value is None: + return default + try: + return float(value) + except ValueError as error: + msg = f"expected float value, got {value!r}" + raise ValueError(msg) from error + + +def parse_int(value: str | None, default: int) -> int: + """Parse an optional integer value with a default. + + Args: + value: Raw environment value. + default: Value returned when `value` is missing. + + Returns: + Parsed integer. + + Raises: + ValueError: If `value` is not an integer. + """ + if value is None: + return default + try: + return int(value) + except ValueError as error: + msg = f"expected integer value, got {value!r}" + raise ValueError(msg) from error + + +def split_csv(value: str) -> list[str]: + """Split a comma-separated environment value. + + Args: + value: Raw comma-separated value. + + Returns: + Non-empty, stripped items. + """ + return [item.strip() for item in value.split(",") if item.strip()] + + def _validate_media_size( media: ChannelMedia, *, @@ -232,6 +464,29 @@ def _matches_text(text: str, patterns: tuple[str, ...]) -> bool: return any(fnmatch.fnmatchcase(text, pattern) for pattern in patterns) +def _exposure_mode(value: str, *, provider: str) -> ExposureMode: + try: + return ExposureMode(value) + except ValueError as error: + modes = ", ".join(mode.value for mode in ExposureMode) + msg = f"invalid {provider} exposure mode {value!r}; expected one of: {modes}" + raise ValueError(msg) from error + + +def _require_open_acknowledgement( + env: Mapping[str, str], + config: ChannelExposureEnv, +) -> None: + if env.get(config.open_ack) == config.open_ack_value: + return + msg = ( + f"{config.provider} exposure mode 'open' allows arbitrary senders to trigger the " + "agent with operator credentials and local host access; set " + f"{config.open_ack}={config.open_ack_value} to acknowledge this risk" + ) + raise ValueError(msg) + + def _split_index(text: str, limit: int) -> int: window = text[:limit] for delimiter in ("\n\n", "\n", " "): diff --git a/libs/talon/deepagents_talon/channels/whatsapp.py b/libs/talon/deepagents_talon/channels/whatsapp.py index fdd30886573..88673d5702f 100644 --- a/libs/talon/deepagents_talon/channels/whatsapp.py +++ b/libs/talon/deepagents_talon/channels/whatsapp.py @@ -23,18 +23,23 @@ from deepagents_talon.channels.base import ( MAX_TEXT_CHARS, ChannelExposure, - ChannelMediaError, + ChannelExposureEnv, ExposureMode, + channel_exposure_from_env, chunk_text, + filter_capped_media_paths, format_markdown_for_channel, max_media_bytes_from_env, + message_with_media_paths, + parse_float, + parse_int, + replace_message_metadata, validate_media, - validate_media_size, ) from deepagents_talon.interfaces import ChannelMedia, ChannelMessage, ChannelStatus, MessageHandler if TYPE_CHECKING: - from collections.abc import Mapping, Sequence + from collections.abc import Mapping from deepagents_talon.config import TalonConfig @@ -51,7 +56,6 @@ DEFAULT_WHATSAPP_MAX_MEDIA_BYTES = 64 * 1024 * 1024 _FAILED_HEALTH_RESTART_THRESHOLD = 3 OPEN_EXPOSURE_ACK_ENV = "DEEPAGENTS_TALON_WHATSAPP_OPEN_ACK" -OPEN_EXPOSURE_ACK_VALUE = "allow-arbitrary-senders" class WhatsAppBridgeError(RuntimeError): @@ -119,7 +123,7 @@ def from_talon_config(cls, config: TalonConfig) -> WhatsAppChannelConfig: """ env = config.env host = env.get("DEEPAGENTS_TALON_WHATSAPP_BRIDGE_HOST", DEFAULT_BRIDGE_HOST) - port = _parse_int(env.get("DEEPAGENTS_TALON_WHATSAPP_BRIDGE_PORT"), DEFAULT_BRIDGE_PORT) + port = parse_int(env.get("DEEPAGENTS_TALON_WHATSAPP_BRIDGE_PORT"), DEFAULT_BRIDGE_PORT) session = Path( env.get("DEEPAGENTS_TALON_WHATSAPP_SESSION_DIR", str(config.channel_dir / "whatsapp")), ) @@ -149,15 +153,15 @@ def from_talon_config(cls, config: TalonConfig) -> WhatsAppChannelConfig: bridge_token=env.get("DEEPAGENTS_TALON_WHATSAPP_BRIDGE_TOKEN") or secrets.token_hex(DEFAULT_BRIDGE_TOKEN_BYTES), max_media_bytes=_whatsapp_max_media_bytes_from_env(env), - poll_interval_seconds=_parse_float( + poll_interval_seconds=parse_float( env.get("DEEPAGENTS_TALON_WHATSAPP_POLL_SECONDS"), DEFAULT_POLL_INTERVAL_SECONDS, ), - health_interval_seconds=_parse_float( + health_interval_seconds=parse_float( env.get("DEEPAGENTS_TALON_WHATSAPP_HEALTH_SECONDS"), DEFAULT_HEALTH_INTERVAL_SECONDS, ), - request_timeout_seconds=_parse_float( + request_timeout_seconds=parse_float( env.get("DEEPAGENTS_TALON_WHATSAPP_REQUEST_TIMEOUT_SECONDS"), DEFAULT_REQUEST_TIMEOUT_SECONDS, ), @@ -628,82 +632,29 @@ def _enforce_inbound_media_cap(message: ChannelMessage, *, max_bytes: int) -> Ch return message mime_types = message.metadata.get("media_mime_types") - kept, kept_mime_types, changed = _filter_inbound_media( - message, + filtered = filter_capped_media_paths( media_paths=media_paths, mime_types=mime_types if isinstance(mime_types, list) else [], max_bytes=max_bytes, ) - if not changed: + for error in filtered.errors: + logger.warning( + "Skipping WhatsApp inbound media for message %s: %s", + message.message_id, + error, + ) + if not filtered.changed: return message - return _with_inbound_media_paths( + checked = message_with_media_paths( message, - media_paths=kept, - mime_types=kept_mime_types, - max_bytes=max_bytes, - ) - - -def _filter_inbound_media( - message: ChannelMessage, - *, - media_paths: Sequence[object], - mime_types: Sequence[object], - max_bytes: int, -) -> tuple[list[str], list[str], bool]: - kept: list[str] = [] - kept_mime_types: list[str] = [] - changed = False - for index, raw_path in enumerate(media_paths): - if not isinstance(raw_path, str): - changed = True - continue - try: - validate_media_size(Path(raw_path), max_bytes=max_bytes) - except FileNotFoundError: - kept.append(raw_path) - except ChannelMediaError as error: - logger.warning( - "Skipping WhatsApp inbound media for message %s: %s", - message.message_id, - error, - ) - changed = True - continue - else: - kept.append(raw_path) - if index < len(mime_types): - mime_type = mime_types[index] - if isinstance(mime_type, str): - kept_mime_types.append(mime_type) - return kept, kept_mime_types, changed - - -def _with_inbound_media_paths( - message: ChannelMessage, - *, - media_paths: list[str], - mime_types: list[str], - max_bytes: int, -) -> ChannelMessage: - metadata = dict(message.metadata) - metadata["media_paths"] = media_paths - metadata["media_path"] = media_paths[0] if media_paths else None - metadata["media_mime_types"] = mime_types - metadata["media_types"] = mime_types - metadata["voice_path"] = ( - media_paths[0] if media_paths and metadata.get("media_type") == "voice" else None + media_paths=filtered.paths, + mime_types=filtered.mime_types, ) - metadata["has_media"] = bool(media_paths) - if not media_paths: + if not filtered.paths: + metadata = dict(checked.metadata) metadata["media_error"] = f"all media files exceeded {max_bytes} bytes" - return ChannelMessage( - conversation_id=message.conversation_id, - text=message.text, - sender_id=message.sender_id, - message_id=message.message_id, - metadata=metadata, - ) + return replace_message_metadata(checked, metadata) + return checked def _parse_status(payload: object) -> ChannelStatus: @@ -782,41 +733,23 @@ def _is_video_type(value: str | None) -> bool: def _exposure_from_env(env: Mapping[str, str]) -> ChannelExposure: - mode = _exposure_mode(env.get("DEEPAGENTS_TALON_WHATSAPP_EXPOSURE", ExposureMode.SELF.value)) - if mode == ExposureMode.OPEN: - _require_open_acknowledgement(env) + exposure = channel_exposure_from_env( + env, + ChannelExposureEnv( + provider="WhatsApp", + exposure="DEEPAGENTS_TALON_WHATSAPP_EXPOSURE", + allowlist_chats="DEEPAGENTS_TALON_WHATSAPP_ALLOWLIST_CHATS", + mention_patterns="DEEPAGENTS_TALON_WHATSAPP_MENTION_PATTERNS", + operator_id="DEEPAGENTS_TALON_WHATSAPP_OPERATOR_ID", + open_ack=OPEN_EXPOSURE_ACK_ENV, + ), + ) + if exposure.mode == ExposureMode.OPEN: logger.warning( "WhatsApp open exposure enabled; arbitrary senders can trigger the agent with " "operator credentials and local host access" ) - conversations = _split_csv(env.get("DEEPAGENTS_TALON_WHATSAPP_ALLOWLIST_CHATS", "")) - mentions = tuple(_split_csv(env.get("DEEPAGENTS_TALON_WHATSAPP_MENTION_PATTERNS", ""))) - return ChannelExposure( - mode=mode, - operator_id=env.get("DEEPAGENTS_TALON_WHATSAPP_OPERATOR_ID"), - conversations=frozenset(conversations), - mention_patterns=mentions, - ) - - -def _exposure_mode(value: str) -> ExposureMode: - try: - return ExposureMode(value) - except ValueError as error: - modes = ", ".join(mode.value for mode in ExposureMode) - msg = f"invalid WhatsApp exposure mode {value!r}; expected one of: {modes}" - raise ValueError(msg) from error - - -def _require_open_acknowledgement(env: Mapping[str, str]) -> None: - if env.get(OPEN_EXPOSURE_ACK_ENV) == OPEN_EXPOSURE_ACK_VALUE: - return - msg = ( - "WhatsApp exposure mode 'open' allows arbitrary senders to trigger the agent with " - "operator credentials and local host access; set " - f"{OPEN_EXPOSURE_ACK_ENV}={OPEN_EXPOSURE_ACK_VALUE} to acknowledge this risk" - ) - raise ValueError(msg) + return exposure def _bridge_command(env: Mapping[str, str]) -> tuple[str, ...] | None: @@ -826,27 +759,3 @@ def _bridge_command(env: Mapping[str, str]) -> tuple[str, ...] | None: if env.get("DEEPAGENTS_TALON_WHATSAPP_START_BRIDGE", "").lower() in {"1", "true", "yes"}: return ("node", str(bridge_script_path())) return None - - -def _split_csv(value: str) -> list[str]: - return [item.strip() for item in value.split(",") if item.strip()] - - -def _parse_int(value: str | None, default: int) -> int: - if value is None: - return default - try: - return int(value) - except ValueError as error: - msg = f"expected integer value, got {value!r}" - raise ValueError(msg) from error - - -def _parse_float(value: str | None, default: float) -> float: - if value is None: - return default - try: - return float(value) - except ValueError as error: - msg = f"expected float value, got {value!r}" - raise ValueError(msg) from error diff --git a/libs/talon/tests/channels/test_whatsapp.py b/libs/talon/tests/channels/test_whatsapp.py index d80aa9e31e1..d39fc1dc3fb 100644 --- a/libs/talon/tests/channels/test_whatsapp.py +++ b/libs/talon/tests/channels/test_whatsapp.py @@ -4,7 +4,7 @@ import json import logging from pathlib import Path -from typing import Self, cast +from typing import TYPE_CHECKING, Self, cast import pytest @@ -24,6 +24,9 @@ from deepagents_talon.config import TalonConfig from deepagents_talon.interfaces import ChannelMedia, ChannelMessage +if TYPE_CHECKING: + import urllib.request + class RecordingTransport: def __init__(self, messages: list[dict[str, object]] | None = None) -> None: @@ -160,7 +163,7 @@ def fake_urlopen(request: object, *, timeout: float) -> JsonResponse: result = transport._request("GET", "/health", None) - request = cast("object", captured["request"]) + request = cast("urllib.request.Request", captured["request"]) assert result == {"success": True} assert captured["timeout"] == 2 assert request.get_header("Authorization") == "Bearer test-token" From 4f3a6e4e46623051d5efadd1b09a0475f6553f8d Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sat, 20 Jun 2026 11:27:50 -0700 Subject: [PATCH 12/48] refactor(talon): simplify Telegram outbound text --- .../deepagents_talon/channels/telegram.py | 186 +++++------------- libs/talon/tests/channels/test_telegram.py | 95 +++------ 2 files changed, 76 insertions(+), 205 deletions(-) diff --git a/libs/talon/deepagents_talon/channels/telegram.py b/libs/talon/deepagents_talon/channels/telegram.py index 2c466b2ad0d..f353e5f27b0 100644 --- a/libs/talon/deepagents_talon/channels/telegram.py +++ b/libs/talon/deepagents_talon/channels/telegram.py @@ -21,10 +21,16 @@ DEFAULT_MAX_MEDIA_BYTES, MAX_TEXT_CHARS, ChannelExposure, + ChannelExposureEnv, ChannelMediaError, ExposureMode, + channel_exposure_from_env, chunk_text, max_media_bytes_from_env, + message_with_media_paths, + parse_float, + replace_message_metadata, + split_csv, validate_media, ) from deepagents_talon.interfaces import ChannelMedia, ChannelMessage, ChannelStatus, MessageHandler @@ -42,14 +48,11 @@ DEFAULT_REQUEST_TIMEOUT_SECONDS = 35.0 MAX_PHOTO_BYTES = 10 * 1024 * 1024 MAX_DOCUMENT_BYTES = 50 * 1024 * 1024 +MAX_CAPTION_CHARS = 1024 OPEN_EXPOSURE_ACK_ENV = "DEEPAGENTS_TALON_TELEGRAM_OPEN_ACK" -OPEN_EXPOSURE_ACK_VALUE = "allow-arbitrary-senders" _OFFSET_FILENAME = "telegram_offset.json" _ALLOWED_UPDATES = ["message", "channel_post"] -# MarkdownV2 special characters that must be escaped. -_MARKDOWNV2_SPECIAL = re.compile(r"([_*\[\]()~`>#=+\-|{}.!\\])") - class TelegramError(RuntimeError): """Raised when the Telegram Bot API reports or causes a transport error.""" @@ -143,22 +146,22 @@ def from_talon_config(cls, config: TalonConfig) -> TelegramChannelConfig: outbound_media_dir=outbound_media_dir, api_base=env.get("DEEPAGENTS_TALON_TELEGRAM_API_BASE", DEFAULT_API_BASE), exposure=exposure, - poll_timeout_seconds=_parse_float( + poll_timeout_seconds=parse_float( env.get("DEEPAGENTS_TALON_TELEGRAM_POLL_TIMEOUT_SECONDS"), DEFAULT_POLL_TIMEOUT_SECONDS, ), - poll_interval_seconds=_parse_float( + poll_interval_seconds=parse_float( env.get("DEEPAGENTS_TALON_TELEGRAM_POLL_INTERVAL_SECONDS"), DEFAULT_POLL_INTERVAL_SECONDS, ), - request_timeout_seconds=_parse_float( + request_timeout_seconds=parse_float( env.get("DEEPAGENTS_TALON_TELEGRAM_REQUEST_TIMEOUT_SECONDS"), DEFAULT_REQUEST_TIMEOUT_SECONDS, ), max_media_bytes=max_media_bytes_from_env(env), operator_id=operator_id, allowed_user_ids=frozenset( - _split_csv(env.get("DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_USERS", "")), + split_csv(env.get("DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_USERS", "")), ), ) @@ -332,27 +335,18 @@ async def stop(self) -> None: self._status = ChannelStatus(provider="telegram", connected=False, detail="disconnected") async def send_message(self, conversation_id: str, text: str) -> None: - """Send chunked text with MarkdownV2 formatting and plain-text fallback. + """Send chunked plain text. Args: conversation_id: Telegram chat id. text: Message content to send. """ for chunk in chunk_text(text, limit=MAX_TEXT_CHARS): - escaped = _escape_markdown_v2(chunk) - try: - await self._transport.call( - "sendMessage", - chat_id=conversation_id, - text=escaped, - parse_mode="MarkdownV2", - ) - except TelegramError: - await self._transport.call( - "sendMessage", - chat_id=conversation_id, - text=chunk, - ) + await self._transport.call( + "sendMessage", + chat_id=conversation_id, + text=chunk, + ) async def send_media(self, conversation_id: str, media: ChannelMedia) -> None: """Send validated image or document media to a Telegram chat. @@ -370,12 +364,11 @@ async def send_media(self, conversation_id: str, media: ChannelMedia) -> None: max_bytes=self.config.max_media_bytes, ) _check_telegram_size(checked) - caption = _escape_markdown_v2(checked.caption) if checked.caption else None + caption = await self._media_caption(conversation_id, checked.caption) if checked.media_type == "image": params: dict[str, object] = {"chat_id": conversation_id} if caption: params["caption"] = caption - params["parse_mode"] = "MarkdownV2" await self._transport.upload( "sendPhoto", file_field="photo", @@ -386,7 +379,6 @@ async def send_media(self, conversation_id: str, media: ChannelMedia) -> None: params = {"chat_id": conversation_id} if caption: params["caption"] = caption - params["parse_mode"] = "MarkdownV2" await self._transport.upload( "sendDocument", file_field="document", @@ -417,22 +409,12 @@ async def edit_message(self, conversation_id: str, message_id: str, text: str) - message_id: Telegram message id. text: Replacement message content. """ - escaped = _escape_markdown_v2(text) - try: - await self._transport.call( - "editMessageText", - chat_id=conversation_id, - message_id=int(message_id), - text=escaped, - parse_mode="MarkdownV2", - ) - except TelegramError: - await self._transport.call( - "editMessageText", - chat_id=conversation_id, - message_id=int(message_id), - text=text, - ) + await self._transport.call( + "editMessageText", + chat_id=conversation_id, + message_id=int(message_id), + text=text, + ) async def status(self) -> ChannelStatus: """Report the most recent Telegram Bot API connection status.""" @@ -463,6 +445,14 @@ async def _identify_bot(self) -> None: detail=f"connected as @{username}" if isinstance(username, str) else "connected", ) + async def _media_caption(self, conversation_id: str, caption: str | None) -> str | None: + if not caption: + return None + if len(caption) <= MAX_CAPTION_CHARS: + return caption + await self.send_message(conversation_id, caption) + return None + async def _poll_updates(self) -> None: while not self._stopped.is_set(): try: @@ -549,29 +539,15 @@ async def _prepare_inbound_media(self, message: ChannelMessage) -> ChannelMessag metadata = dict(message.metadata) metadata["has_media"] = False metadata["media_error"] = str(error) - return ChannelMessage( - conversation_id=message.conversation_id, - text=message.text, - sender_id=message.sender_id, - message_id=message.message_id, - metadata=metadata, - ) + return replace_message_metadata(message, metadata) metadata = dict(message.metadata) path = str(destination) - metadata["has_media"] = True - metadata["media_paths"] = [path] - metadata["media_path"] = path - if media_type == "voice": - metadata["voice_path"] = path mime_type = _downloaded_mime_type(destination, metadata) - if mime_type is not None: - metadata["media_mime_types"] = [mime_type] - return ChannelMessage( - conversation_id=message.conversation_id, - text=message.text, - sender_id=message.sender_id, - message_id=message.message_id, - metadata=metadata, + message = replace_message_metadata(message, metadata) + return message_with_media_paths( + message, + media_paths=[path], + mime_types=[mime_type] if mime_type is not None else [], ) async def _download_inbound_media( @@ -629,18 +605,6 @@ def timeout(self) -> float: return self.config.request_timeout_seconds -def _escape_markdown_v2(text: str) -> str: - """Escape MarkdownV2 special characters. - - Args: - text: Plain text to escape. - - Returns: - Text with all MarkdownV2 special characters escaped. - """ - return _MARKDOWNV2_SPECIAL.sub(r"\\\1", text) - - def _check_telegram_size(media: ChannelMedia) -> None: """Validate media size against Telegram-specific limits. @@ -748,13 +712,7 @@ def _with_from_self(message: ChannelMessage, bot_id: str | None) -> ChannelMessa return message metadata = dict(message.metadata) metadata["from_self"] = True - return ChannelMessage( - conversation_id=message.conversation_id, - text=message.text, - sender_id=message.sender_id, - message_id=message.message_id, - metadata=metadata, - ) + return replace_message_metadata(message, metadata) def _allows_telegram_message( @@ -1083,62 +1041,24 @@ def _exposure_from_env(env: Mapping[str, str]) -> ChannelExposure: Raises: ValueError: If the exposure mode is invalid or open mode is not acknowledged. """ - mode = _exposure_mode(env.get("DEEPAGENTS_TALON_TELEGRAM_EXPOSURE", ExposureMode.SELF.value)) - operator_id = env.get("DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID") or None - if mode == ExposureMode.SELF and operator_id is None: - msg = ( - "Telegram self exposure requires DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID; " - "set DEEPAGENTS_TALON_TELEGRAM_EXPOSURE=allowlist or open for other modes" - ) - raise ValueError(msg) - if mode == ExposureMode.OPEN: - _require_open_acknowledgement(env) + exposure = channel_exposure_from_env( + env, + ChannelExposureEnv( + provider="Telegram", + exposure="DEEPAGENTS_TALON_TELEGRAM_EXPOSURE", + allowlist_chats="DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_CHATS", + mention_patterns="DEEPAGENTS_TALON_TELEGRAM_MENTION_PATTERNS", + operator_id="DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID", + open_ack=OPEN_EXPOSURE_ACK_ENV, + require_self_operator=True, + ), + ) + if exposure.mode == ExposureMode.OPEN: logger.warning( "Telegram open exposure enabled; arbitrary senders can trigger the agent with " "operator credentials and local host access", ) - conversations = _split_csv(env.get("DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_CHATS", "")) - mentions = tuple(_split_csv(env.get("DEEPAGENTS_TALON_TELEGRAM_MENTION_PATTERNS", ""))) - return ChannelExposure( - mode=mode, - operator_id=operator_id, - conversations=frozenset(conversations), - mention_patterns=mentions, - ) - - -def _exposure_mode(value: str) -> ExposureMode: - try: - return ExposureMode(value) - except ValueError as error: - modes = ", ".join(mode.value for mode in ExposureMode) - msg = f"invalid Telegram exposure mode {value!r}; expected one of: {modes}" - raise ValueError(msg) from error - - -def _require_open_acknowledgement(env: Mapping[str, str]) -> None: - if env.get(OPEN_EXPOSURE_ACK_ENV) == OPEN_EXPOSURE_ACK_VALUE: - return - msg = ( - "Telegram exposure mode 'open' allows arbitrary senders to trigger the agent with " - "operator credentials and local host access; set " - f"{OPEN_EXPOSURE_ACK_ENV}={OPEN_EXPOSURE_ACK_VALUE} to acknowledge this risk" - ) - raise ValueError(msg) - - -def _split_csv(value: str) -> list[str]: - return [item.strip() for item in value.split(",") if item.strip()] - - -def _parse_float(value: str | None, default: float) -> float: - if value is None: - return default - try: - return float(value) - except ValueError as error: - msg = f"expected float value, got {value!r}" - raise ValueError(msg) from error + return exposure # --- Offset persistence (ticket 23) --- diff --git a/libs/talon/tests/channels/test_telegram.py b/libs/talon/tests/channels/test_telegram.py index 5898bf76a3c..7ef747a9d8b 100644 --- a/libs/talon/tests/channels/test_telegram.py +++ b/libs/talon/tests/channels/test_telegram.py @@ -24,7 +24,6 @@ TelegramTransport, _download_file, _encode_multipart_form, - _escape_markdown_v2, _load_offset, _save_offset, ) @@ -98,24 +97,6 @@ async def call(self, method: str, **params: object) -> object: # noqa: ARG002 return {"ok": True, "result": True} -class MarkdownV2ErrorTransport: - """Transport that fails MarkdownV2 messages, forcing plain-text fallback.""" - - def __init__(self) -> None: - self.calls: list[tuple[str, dict[str, object]]] = [] - - async def call(self, method: str, **params: object) -> object: - self.calls.append((method, dict(params))) - if method == "getMe": - return {"ok": True, "result": {"id": 123456, "username": "test_bot"}} - if method == "getUpdates": - return {"ok": True, "result": []} - if params.get("parse_mode") == "MarkdownV2": - msg = "Bad Request: can't parse entities" - raise TelegramError(msg) - return {"ok": True, "result": {"message_id": 42}} - - def _make_update( # noqa: PLR0913 # test helper with many optional fields *, update_id: int = 1, @@ -312,21 +293,6 @@ def test_config_accepts_open_exposure_with_acknowledgement(tmp_path: Path) -> No assert telegram.exposure.mode == ExposureMode.OPEN -# --- MarkdownV2 escaping tests --- - - -def test_escape_markdown_v2_escapes_special_chars() -> None: - assert _escape_markdown_v2("hello *world*") == r"hello \*world\*" - assert _escape_markdown_v2("a_b_c") == r"a\_b\_c" - assert _escape_markdown_v2("list [1]") == r"list \[1\]" - assert _escape_markdown_v2("not! really.") == r"not\! really\." - assert _escape_markdown_v2("plain text") == "plain text" - - -def test_escape_markdown_v2_escapes_backslash() -> None: - assert _escape_markdown_v2(r"path\to") == r"path\\to" - - # --- Polling and exposure tests --- @@ -544,7 +510,7 @@ async def test_channel_identifies_bot_on_start(tmp_path: Path) -> None: # --- Outbound text tests --- -async def test_send_message_uses_markdown_v2(tmp_path: Path) -> None: +async def test_send_message_uses_plain_text(tmp_path: Path) -> None: transport = RecordingTransport() channel = TelegramChannel( _make_config(tmp_path), @@ -555,26 +521,11 @@ async def test_send_message_uses_markdown_v2(tmp_path: Path) -> None: assert transport.calls[0][0] == "sendMessage" params = transport.calls[0][1] - assert params["parse_mode"] == "MarkdownV2" - assert params["text"] == r"hello \*world\*" + assert "parse_mode" not in params + assert params["text"] == "hello *world*" assert params["chat_id"] == "123" -async def test_send_message_falls_back_to_plain_text(tmp_path: Path) -> None: - transport = MarkdownV2ErrorTransport() - channel = TelegramChannel( - _make_config(tmp_path), - transport=cast("TelegramTransport", transport), - ) - - await channel.send_message("123", "hello *world*") - - # First call uses MarkdownV2, second is plain text fallback. - assert transport.calls[0][1]["parse_mode"] == "MarkdownV2" - assert "parse_mode" not in transport.calls[1][1] - assert transport.calls[1][1]["text"] == "hello *world*" - - async def test_send_message_chunks_long_text(tmp_path: Path) -> None: transport = RecordingTransport() channel = TelegramChannel( @@ -610,7 +561,7 @@ async def test_send_media_sends_photo_for_images(tmp_path: Path) -> None: "sendPhoto", "photo", image, - {"chat_id": "123", "caption": "cap", "parse_mode": "MarkdownV2"}, + {"chat_id": "123", "caption": "cap"}, ), ] @@ -629,6 +580,22 @@ async def test_send_media_sends_document_for_videos(tmp_path: Path) -> None: assert transport.uploads == [("sendDocument", "document", video, {"chat_id": "123"})] +async def test_send_media_sends_long_caption_as_text_before_upload(tmp_path: Path) -> None: + transport = RecordingTransport() + image = tmp_path / "image.png" + image.write_bytes(b"image-data") + channel = TelegramChannel( + _make_config(tmp_path), + transport=cast("TelegramTransport", transport), + ) + + caption = "x" * 1025 + await channel.send_media("123", ChannelMedia(path=image, media_type="image", caption=caption)) + + assert transport.calls[0] == ("sendMessage", {"chat_id": "123", "text": caption}) + assert transport.uploads == [("sendPhoto", "photo", image, {"chat_id": "123"})] + + def test_multipart_form_encodes_local_file_upload(tmp_path: Path) -> None: image = tmp_path / "image.png" image.write_bytes(b"image-data") @@ -716,7 +683,7 @@ async def test_send_media_rejects_oversized_document( # --- Edit message tests --- -async def test_edit_message_uses_markdown_v2(tmp_path: Path) -> None: +async def test_edit_message_uses_plain_text(tmp_path: Path) -> None: transport = RecordingTransport() channel = TelegramChannel( _make_config(tmp_path), @@ -726,27 +693,11 @@ async def test_edit_message_uses_markdown_v2(tmp_path: Path) -> None: await channel.edit_message("123", "42", "updated *text*") assert transport.calls[0][0] == "editMessageText" - assert transport.calls[0][1]["parse_mode"] == "MarkdownV2" - assert transport.calls[0][1]["text"] == r"updated \*text\*" + assert "parse_mode" not in transport.calls[0][1] + assert transport.calls[0][1]["text"] == "updated *text*" assert transport.calls[0][1]["message_id"] == 42 -async def test_edit_message_falls_back_to_plain_text(tmp_path: Path) -> None: - transport = MarkdownV2ErrorTransport() - channel = TelegramChannel( - _make_config(tmp_path), - transport=cast("TelegramTransport", transport), - ) - - await channel.edit_message("123", "42", "updated *text*") - - edit_calls = [c for c in transport.calls if c[0] == "editMessageText"] - assert len(edit_calls) == 2 - assert edit_calls[0][1]["parse_mode"] == "MarkdownV2" - assert "parse_mode" not in edit_calls[1][1] - assert edit_calls[1][1]["text"] == "updated *text*" - - # --- Typing indicator tests --- From 333e19085fe9a2a439189a571d03996937ac500b Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sat, 20 Jun 2026 12:18:51 -0700 Subject: [PATCH 13/48] fix(talon): support multiple operator ids --- libs/talon/README.md | 4 +-- libs/talon/deepagents_talon/channels/base.py | 27 +++++++++++++----- .../deepagents_talon/channels/telegram.py | 7 +++-- libs/talon/tests/channels/test_base.py | 15 ++++++++++ libs/talon/tests/channels/test_telegram.py | 28 +++++++++++++++++++ libs/talon/tests/channels/test_whatsapp.py | 26 +++++++++++++++++ 6 files changed, 95 insertions(+), 12 deletions(-) diff --git a/libs/talon/README.md b/libs/talon/README.md index ba0d9925d4b..eb4e79c61da 100644 --- a/libs/talon/README.md +++ b/libs/talon/README.md @@ -67,7 +67,7 @@ AGENT_MODEL=: \ uv run deepagents-talon --whatsapp ``` -The bridge prints a QR code during pairing. By default, inbound exposure is `self`, so only messages from the paired account trigger the agent. Configure `DEEPAGENTS_TALON_WHATSAPP_EXPOSURE=allowlist` with `DEEPAGENTS_TALON_WHATSAPP_ALLOWLIST_CHATS` or `DEEPAGENTS_TALON_WHATSAPP_MENTION_PATTERNS` to allow specific chats. Outbound WhatsApp messages include a `deepagents bot` header by default so self-message conversations clearly distinguish agent replies from operator messages. Set `DEEPAGENTS_TALON_WHATSAPP_BOT_HEADER` to customize that label. Markdown image/video references in assistant replies may attach files only when they are relative paths inside `DEEPAGENTS_TALON_OUTBOUND_MEDIA_DIR`, or inside `DEEPAGENTS_TALON_WORKSPACE` when no outbound media directory is configured. `DEEPAGENTS_TALON_MAX_MEDIA_BYTES` caps inbound and outbound channel media across providers and defaults to `1073741824` (1 GiB), but WhatsApp is clamped to `67108864` (64 MiB) because the bridge library materializes downloads in memory before writing them. +The bridge prints a QR code during pairing. By default, inbound exposure is `self`, so only messages from the paired account trigger the agent. Configure `DEEPAGENTS_TALON_WHATSAPP_EXPOSURE=allowlist` with `DEEPAGENTS_TALON_WHATSAPP_ALLOWLIST_CHATS` or `DEEPAGENTS_TALON_WHATSAPP_MENTION_PATTERNS` to allow specific chats. `DEEPAGENTS_TALON_WHATSAPP_OPERATOR_ID` accepts one or more comma-separated operator IDs for `self` exposure. Outbound WhatsApp messages include a `deepagents bot` header by default so self-message conversations clearly distinguish agent replies from operator messages. Set `DEEPAGENTS_TALON_WHATSAPP_BOT_HEADER` to customize that label. Markdown image/video references in assistant replies may attach files only when they are relative paths inside `DEEPAGENTS_TALON_OUTBOUND_MEDIA_DIR`, or inside `DEEPAGENTS_TALON_WORKSPACE` when no outbound media directory is configured. `DEEPAGENTS_TALON_MAX_MEDIA_BYTES` caps inbound and outbound channel media across providers and defaults to `1073741824` (1 GiB), but WhatsApp is clamped to `67108864` (64 MiB) because the bridge library materializes downloads in memory before writing them. Inbound voice transcription is opt-in: @@ -114,7 +114,7 @@ AGENT_MODEL=: \ uv run --directory libs/talon deepagents-talon --telegram ``` -In `allowlist` mode, `DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_USERS` allows private bot DMs from specific Telegram user IDs, while `DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_CHATS` allows channel posts from specific channel chat IDs. `DEEPAGENTS_TALON_MAX_MEDIA_BYTES` caps inbound and outbound channel media across providers and defaults to `1073741824` (1 GiB); Telegram's smaller Bot API upload limits still apply. If `AGENT_MODEL`, `DEEPAGENTS_TALON_MODEL`, and `DEEPAGENTS_TALON_FLEET_DIR` are all unset, Talon uses the echo runtime and replies with the inbound text unchanged. +In `allowlist` mode, `DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_USERS` allows private bot DMs from specific Telegram user IDs, while `DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_CHATS` allows channel posts from specific channel chat IDs. `DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID` accepts one or more comma-separated operator IDs for `self` exposure. `DEEPAGENTS_TALON_MAX_MEDIA_BYTES` caps inbound and outbound channel media across providers and defaults to `1073741824` (1 GiB); Telegram's smaller Bot API upload limits still apply. If `AGENT_MODEL`, `DEEPAGENTS_TALON_MODEL`, and `DEEPAGENTS_TALON_FLEET_DIR` are all unset, Talon uses the echo runtime and replies with the inbound text unchanged. ## Tracing diff --git a/libs/talon/deepagents_talon/channels/base.py b/libs/talon/deepagents_talon/channels/base.py index a3d0791c2be..7bd446e27d6 100644 --- a/libs/talon/deepagents_talon/channels/base.py +++ b/libs/talon/deepagents_talon/channels/base.py @@ -53,7 +53,7 @@ class ChannelExposureEnv: exposure: Environment variable containing the exposure mode. allowlist_chats: Environment variable containing allowlisted chats. mention_patterns: Environment variable containing allowlist text patterns. - operator_id: Environment variable containing the trusted operator id. + operator_id: Environment variable containing trusted operator ids. open_ack: Environment variable acknowledging open-exposure risk. open_ack_value: Required acknowledgement value for open exposure. require_self_operator: Whether `self` exposure requires an operator id. @@ -92,15 +92,26 @@ class ChannelExposure: Args: mode: Trigger policy for inbound messages. - operator_id: Channel-specific id for the operator's own account. + operator_id: Channel-specific id for the operator's own account. Preserved + for callers that configure a single operator. conversations: Conversation ids allowed in allowlist mode. mention_patterns: Glob-style patterns that may allow a message by text. + operator_ids: Channel-specific ids for operator accounts that may trigger + `self` exposure. """ mode: ExposureMode = ExposureMode.SELF operator_id: str | None = None conversations: frozenset[str] = field(default_factory=frozenset) mention_patterns: tuple[str, ...] = () + operator_ids: frozenset[str] = field(default_factory=frozenset, kw_only=True) + + def __post_init__(self) -> None: + """Normalize the legacy single-operator field into the operator id set.""" + operator_ids = set(self.operator_ids) + if self.operator_id is not None: + operator_ids.add(self.operator_id) + object.__setattr__(self, "operator_ids", frozenset(operator_ids)) def allows(self, message: ChannelMessage) -> bool: """Return whether an inbound message may trigger the agent. @@ -114,7 +125,7 @@ def allows(self, message: ChannelMessage) -> bool: if self.mode == ExposureMode.OPEN: return True if self.mode == ExposureMode.SELF: - return _is_self_message(message, self.operator_id) + return _is_self_message(message, self.operator_ids) return message.conversation_id in self.conversations or _matches_text( message.text, self.mention_patterns, @@ -185,8 +196,9 @@ def channel_exposure_from_env( env.get(config.exposure, ExposureMode.SELF.value), provider=config.provider, ) - operator_id = env.get(config.operator_id) or None - if mode == ExposureMode.SELF and config.require_self_operator and operator_id is None: + operator_ids = tuple(split_csv(env.get(config.operator_id, ""))) + operator_id = operator_ids[0] if operator_ids else None + if mode == ExposureMode.SELF and config.require_self_operator and not operator_ids: msg = ( f"{config.provider} self exposure requires {config.operator_id}; " f"set {config.exposure}=allowlist or open for other modes" @@ -199,6 +211,7 @@ def channel_exposure_from_env( operator_id=operator_id, conversations=frozenset(split_csv(env.get(config.allowlist_chats, ""))), mention_patterns=tuple(split_csv(env.get(config.mention_patterns, ""))), + operator_ids=frozenset(operator_ids), ) @@ -454,10 +467,10 @@ def _validate_media_size( return ChannelMedia(path=path, media_type=media.media_type, caption=media.caption) -def _is_self_message(message: ChannelMessage, operator_id: str | None) -> bool: +def _is_self_message(message: ChannelMessage, operator_ids: frozenset[str]) -> bool: if message.metadata.get("from_self") is True: return True - return operator_id is not None and message.sender_id == operator_id + return message.sender_id is not None and message.sender_id in operator_ids def _matches_text(text: str, patterns: tuple[str, ...]) -> bool: diff --git a/libs/talon/deepagents_talon/channels/telegram.py b/libs/talon/deepagents_talon/channels/telegram.py index f353e5f27b0..5ea42a2a519 100644 --- a/libs/talon/deepagents_talon/channels/telegram.py +++ b/libs/talon/deepagents_talon/channels/telegram.py @@ -84,7 +84,8 @@ class TelegramChannelConfig: request_timeout_seconds: Per-request HTTP timeout for Bot API calls. max_media_bytes: Maximum media bytes allowed for inbound downloads and outbound local files before provider-specific limits are applied. - operator_id: Telegram user ID for the operator (self exposure mode). + operator_id: First Telegram user ID for the operator, preserved for + compatibility with single-operator callers in self exposure mode. allowed_user_ids: Telegram user IDs allowed to trigger private chats in allowlist exposure mode. """ @@ -138,7 +139,6 @@ def from_talon_config(cls, config: TalonConfig) -> TelegramChannelConfig: or "/workspace", ) exposure = _exposure_from_env(env) - operator_id = env.get("DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID") return cls( bot_token=token, session_dir=session, @@ -159,7 +159,7 @@ def from_talon_config(cls, config: TalonConfig) -> TelegramChannelConfig: DEFAULT_REQUEST_TIMEOUT_SECONDS, ), max_media_bytes=max_media_bytes_from_env(env), - operator_id=operator_id, + operator_id=exposure.operator_id, allowed_user_ids=frozenset( split_csv(env.get("DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_USERS", "")), ), @@ -701,6 +701,7 @@ def _effective_exposure( if ( exposure.mode != ExposureMode.SELF or exposure.operator_id is not None + or exposure.operator_ids or operator_id is None ): return exposure diff --git a/libs/talon/tests/channels/test_base.py b/libs/talon/tests/channels/test_base.py index 0a0017263d9..690ede839b9 100644 --- a/libs/talon/tests/channels/test_base.py +++ b/libs/talon/tests/channels/test_base.py @@ -20,6 +20,7 @@ def test_default_exposure_allows_only_self_messages() -> None: exposure = ChannelExposure(operator_id="operator") + assert exposure.operator_ids == frozenset({"operator"}) assert exposure.allows(ChannelMessage(conversation_id="chat", text="hi", sender_id="operator")) assert exposure.allows( ChannelMessage( @@ -32,6 +33,20 @@ def test_default_exposure_allows_only_self_messages() -> None: assert not exposure.allows(ChannelMessage(conversation_id="chat", text="hi", sender_id="other")) +def test_default_exposure_allows_multiple_operator_ids() -> None: + exposure = ChannelExposure( + operator_id="operator", + operator_ids=frozenset({"backup-operator"}), + ) + + assert exposure.operator_ids == frozenset({"operator", "backup-operator"}) + assert exposure.allows(ChannelMessage(conversation_id="chat", text="hi", sender_id="operator")) + assert exposure.allows( + ChannelMessage(conversation_id="chat", text="hi", sender_id="backup-operator") + ) + assert not exposure.allows(ChannelMessage(conversation_id="chat", text="hi", sender_id="other")) + + def test_allowlist_exposure_allows_chats_and_mention_patterns() -> None: exposure = ChannelExposure( mode=ExposureMode.ALLOWLIST, diff --git a/libs/talon/tests/channels/test_telegram.py b/libs/talon/tests/channels/test_telegram.py index 7ef747a9d8b..497449d6f06 100644 --- a/libs/talon/tests/channels/test_telegram.py +++ b/libs/talon/tests/channels/test_telegram.py @@ -209,6 +209,34 @@ def test_config_from_talon_env_maps_telegram_values(tmp_path: Path) -> None: assert telegram.max_media_bytes == DEFAULT_MAX_MEDIA_BYTES +def test_config_from_talon_env_maps_multiple_operator_ids(tmp_path: Path) -> None: + config = TalonConfig.from_env( + { + "AGENT_ASSISTANT_ID": "assistant", + "DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN": "secret-token", + "DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID": "999, 1000", + }, + base_home=tmp_path, + ) + + telegram = TelegramChannelConfig.from_talon_config(config) + + assert telegram.operator_id == "999" + assert telegram.exposure == ChannelExposure( + operator_id="999", + operator_ids=frozenset({"999", "1000"}), + ) + assert telegram.exposure.allows( + ChannelMessage(conversation_id="chat", text="hi", sender_id="999") + ) + assert telegram.exposure.allows( + ChannelMessage(conversation_id="chat", text="hi", sender_id="1000") + ) + assert not telegram.exposure.allows( + ChannelMessage(conversation_id="chat", text="hi", sender_id="1001") + ) + + def test_config_from_talon_env_maps_max_media_bytes(tmp_path: Path) -> None: config = TalonConfig.from_env( { diff --git a/libs/talon/tests/channels/test_whatsapp.py b/libs/talon/tests/channels/test_whatsapp.py index d39fc1dc3fb..8e84d531b2c 100644 --- a/libs/talon/tests/channels/test_whatsapp.py +++ b/libs/talon/tests/channels/test_whatsapp.py @@ -104,6 +104,32 @@ def test_config_from_talon_env_maps_exposure( assert whatsapp.bot_header == "test bot" +def test_config_from_talon_env_maps_multiple_operator_ids(tmp_path: Path) -> None: + config = TalonConfig.from_env( + { + "AGENT_ASSISTANT_ID": "assistant", + "DEEPAGENTS_TALON_WHATSAPP_OPERATOR_ID": "operator, backup-operator", + }, + base_home=tmp_path, + ) + + whatsapp = WhatsAppChannelConfig.from_talon_config(config) + + assert whatsapp.exposure == ChannelExposure( + operator_id="operator", + operator_ids=frozenset({"operator", "backup-operator"}), + ) + assert whatsapp.exposure.allows( + ChannelMessage(conversation_id="chat", text="hi", sender_id="operator") + ) + assert whatsapp.exposure.allows( + ChannelMessage(conversation_id="chat", text="hi", sender_id="backup-operator") + ) + assert not whatsapp.exposure.allows( + ChannelMessage(conversation_id="chat", text="hi", sender_id="other") + ) + + def test_config_from_talon_env_maps_max_media_bytes(tmp_path: Path) -> None: config = TalonConfig.from_env( { From 1b20fd3dc531d3883781c35cbda7990715a31fcc Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sat, 20 Jun 2026 13:23:46 -0700 Subject: [PATCH 14/48] chore(talon): reduce Telegram adapter PR size --- examples/talon-docker/.env.example | 34 -- examples/talon-docker/README.md | 155 -------- examples/talon-whatsapp/.env.example | 25 ++ .../AGENTS.md | 0 .../Dockerfile | 4 +- examples/talon-whatsapp/README.md | 62 +++ .../docker-compose.yml | 12 +- libs/talon/README.md | 4 +- libs/talon/tests/channels/test_telegram.py | 358 +++++++----------- .../integration_tests/test_telegram_host.py | 134 ++----- 10 files changed, 266 insertions(+), 522 deletions(-) delete mode 100644 examples/talon-docker/.env.example delete mode 100644 examples/talon-docker/README.md create mode 100644 examples/talon-whatsapp/.env.example rename examples/{talon-docker => talon-whatsapp}/AGENTS.md (100%) rename examples/{talon-docker => talon-whatsapp}/Dockerfile (94%) create mode 100644 examples/talon-whatsapp/README.md rename examples/{talon-docker => talon-whatsapp}/docker-compose.yml (57%) diff --git a/examples/talon-docker/.env.example b/examples/talon-docker/.env.example deleted file mode 100644 index 103b51df1be..00000000000 --- a/examples/talon-docker/.env.example +++ /dev/null @@ -1,34 +0,0 @@ -# Runtime -AGENT_ASSISTANT_ID=talon-docker-local -AGENT_MODEL= - -# Provider credentials. Keep real values only in your local `.env`. -OPENAI_API_KEY= -ANTHROPIC_API_KEY= - -# WhatsApp is enabled by default for this example. -# Scan the QR code with your phone to bridge WhatsApp to Talon. Set allowlists and mention patterns to control exposure. -DEEPAGENTS_TALON_WHATSAPP_ENABLED=true -DEEPAGENTS_TALON_WHATSAPP_START_BRIDGE=true -DEEPAGENTS_TALON_WHATSAPP_EXPOSURE=self -DEEPAGENTS_TALON_WHATSAPP_ALLOWLIST_CHATS= -DEEPAGENTS_TALON_WHATSAPP_MENTION_PATTERNS= - -# Telegram is disabled by default. Set the bot token and allowlists before enabling. -# Ask @botfather for a bot token to enable Telegram integration. -# Ask @userinfobbot for user and chat IDs to populate the allowlists. -DEEPAGENTS_TALON_TELEGRAM_ENABLED=false -DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN= -DEEPAGENTS_TALON_TELEGRAM_EXPOSURE=allowlist -DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_USERS= -DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_CHATS= -DEEPAGENTS_TALON_TELEGRAM_MENTION_PATTERNS= - -# Voice transcription applies to inbound channel media. -DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_ENABLED=true -DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_DEVICE=cpu - -# Optional tracing. -LANGSMITH_TRACING=false -LANGSMITH_API_KEY= -LANGSMITH_PROJECT=deepagents-talon diff --git a/examples/talon-docker/README.md b/examples/talon-docker/README.md deleted file mode 100644 index c0798601faa..00000000000 --- a/examples/talon-docker/README.md +++ /dev/null @@ -1,155 +0,0 @@ -# Talon Docker Example - -This example runs one Deep Agents Talon host in Docker. It can run WhatsApp, -Telegram, or both channels against the same local assistant state and workspace. - -> **Experimental:** Talon is an experimental runtime and is subject to change or -> removal at any time. - -The host `~/agent-workspace/` directory is mounted at `/workspace`. Cron records, -downloaded inbound media, channel session state, and agent-created files persist -under that host directory. - -## Run - -```bash -cp .env.example .env -mkdir -p ~/agent-workspace - -# Fill AGENT_MODEL and the required provider credentials in .env. -# Enable the channels you want, then build once and run: -docker compose build -docker compose up -``` - -The image installs the Talon package at build time. Rebuild after changing the -Dockerfile, system packages, Node dependencies, or Talon Python dependencies. - -## Channel Setup - -### WhatsApp - -The sample `.env.example` enables WhatsApp by default: - -```bash -DEEPAGENTS_TALON_WHATSAPP_ENABLED=true -DEEPAGENTS_TALON_WHATSAPP_START_BRIDGE=true -DEEPAGENTS_TALON_WHATSAPP_EXPOSURE=self -``` - -On first run, scan the QR code printed by the bridge. With `self` exposure, only -messages from the paired WhatsApp account trigger the agent. Use `allowlist` or -`open` only when you intentionally want other chats to trigger the agent. - -Voice transcription is enabled in the sample env. The image installs `ffmpeg` and -the Talon `speech` extra so inbound WhatsApp voice notes are transcribed locally -with NVIDIA Parakeet through Transformers before reaching the agent. The first -voice message can be slow because the ASR model is downloaded lazily. Set -`DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_DEVICE=cuda` on GPU-enabled hosts. - -### Telegram - -Create a Telegram bot with BotFather, add its token to `.env`, and enable the -Telegram channel: - -```bash -DEEPAGENTS_TALON_TELEGRAM_ENABLED=true -DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN= -DEEPAGENTS_TALON_TELEGRAM_EXPOSURE=allowlist -DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_USERS=123456789 -DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_CHATS=-1001234567890 -``` - -Use `DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_USERS` for private bot DMs from specific -Telegram user IDs. Use `DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_CHATS` for channel -posts from specific Telegram channel chat IDs. Channel chat IDs are usually -negative and often start with `-100`. - -To process Telegram channel posts, add the bot to the channel with permission to -read posts. If you only want private DMs, leave `ALLOWLIST_CHATS` empty. If you -only want channel posts, leave `ALLOWLIST_USERS` empty. - -## Example Env Values - -The tracked `.env.example` uses placeholder-only values. Keep real provider keys -and bot tokens in your local `.env`, which is ignored by git. - -```bash -AGENT_ASSISTANT_ID=talon-docker-local -AGENT_MODEL= - -DEEPAGENTS_TALON_WHATSAPP_ENABLED=true -DEEPAGENTS_TALON_TELEGRAM_ENABLED=false - -DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN= -DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_USERS= -DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_CHATS= - -LANGSMITH_TRACING=false -LANGSMITH_API_KEY= -``` - -`AGENT_MODEL` selects the Deep Agents chat model. If it is unset, Talon runs the -echo runtime for smoke tests and replies with the inbound text unchanged. - -The Docker example overrides `DEEPAGENTS_TALON_HOME` to -`/workspace/.deepagents`, so cron jobs are stored at -`~/agent-workspace/.deepagents//cron/jobs.json`. Assistant Markdown -image/video attachments must use relative paths inside -`DEEPAGENTS_TALON_OUTBOUND_MEDIA_DIR`, or inside `DEEPAGENTS_TALON_WORKSPACE` -when no outbound media directory is configured. - -Set `LANGSMITH_TRACING=true` and `LANGSMITH_API_KEY` to trace each channel or -cron-triggered run. `LANGSMITH_PROJECT` defaults to `deepagents-talon`. - -## Local Run Without Docker - -```bash -cp .env.example .env -set -a -. ./.env -set +a - -cd ../../libs/talon/deepagents_talon/channels/whatsapp_bridge -npm install - -cd ../../../.. -uv sync --directory libs/talon --extra speech -cp examples/talon-docker/AGENTS.md ~/.deepagents/talon-docker-local/agent/AGENTS.md -export DEEPAGENTS_TALON_WORKSPACE=~/agent-workspace -uv run --directory libs/talon deepagents-talon -``` - -## Exposure Reference - -WhatsApp exposure: - -- `DEEPAGENTS_TALON_WHATSAPP_EXPOSURE=self` allows only messages from the paired - account. -- `DEEPAGENTS_TALON_WHATSAPP_EXPOSURE=allowlist` allows chats in - `DEEPAGENTS_TALON_WHATSAPP_ALLOWLIST_CHATS` or messages matching - `DEEPAGENTS_TALON_WHATSAPP_MENTION_PATTERNS`. -- `DEEPAGENTS_TALON_WHATSAPP_EXPOSURE=open` allows every inbound WhatsApp - message and requires `DEEPAGENTS_TALON_WHATSAPP_OPEN_ACK=allow-arbitrary-senders`. - -Telegram exposure: - -- `DEEPAGENTS_TALON_TELEGRAM_EXPOSURE=self` allows only messages from - `DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID`. -- `DEEPAGENTS_TALON_TELEGRAM_EXPOSURE=allowlist` allows private DMs from - `DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_USERS`, channel posts from - `DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_CHATS`, or messages matching - `DEEPAGENTS_TALON_TELEGRAM_MENTION_PATTERNS`. -- `DEEPAGENTS_TALON_TELEGRAM_EXPOSURE=open` allows every inbound Telegram - message and requires `DEEPAGENTS_TALON_TELEGRAM_OPEN_ACK=allow-arbitrary-senders`. - -Cron jobs are stored in the assistant state directory at `cron/jobs.json`. -Scheduler ticks, dispatch, success/failure, and delivery outcomes are logged as -`talon_event` JSON records. - -## Resources - -- [LangChain Academy](https://academy.langchain.com/) - Comprehensive, free - courses on LangChain libraries and products, made by the LangChain team. -- [Code of Conduct](https://github.com/langchain-ai/langchain/?tab=coc-ov-file) - - community guidelines and standards diff --git a/examples/talon-whatsapp/.env.example b/examples/talon-whatsapp/.env.example new file mode 100644 index 00000000000..494323b64b7 --- /dev/null +++ b/examples/talon-whatsapp/.env.example @@ -0,0 +1,25 @@ +# Required assistant identity and model. +AGENT_ASSISTANT_ID=whatsapp-local +AGENT_MODEL=openai:gpt-5.2 +DEEPAGENTS_TALON_CONTEXT_SIZE=75000 +OPENAI_API_KEY= + +# Optional LangSmith tracing. Traces are emitted only when both are set. +LANGSMITH_TRACING=false +LANGSMITH_API_KEY= +LANGSMITH_PROJECT=deepagents-talon + +# WhatsApp channel. +DEEPAGENTS_TALON_WHATSAPP_ENABLED=true +DEEPAGENTS_TALON_WHATSAPP_EXPOSURE=self +DEEPAGENTS_TALON_WHATSAPP_OPERATOR_ID= +DEEPAGENTS_TALON_WHATSAPP_ALLOWLIST_CHATS= +DEEPAGENTS_TALON_WHATSAPP_MENTION_PATTERNS= +DEEPAGENTS_TALON_WHATSAPP_BRIDGE_HOST=127.0.0.1 +DEEPAGENTS_TALON_WHATSAPP_BRIDGE_PORT=3000 +DEEPAGENTS_TALON_WHATSAPP_START_BRIDGE=true + +# Voice transcription. +# Uses local NVIDIA Parakeet through Transformers. First use downloads the model. +DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_ENABLED=true +DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_DEVICE=cpu diff --git a/examples/talon-docker/AGENTS.md b/examples/talon-whatsapp/AGENTS.md similarity index 100% rename from examples/talon-docker/AGENTS.md rename to examples/talon-whatsapp/AGENTS.md diff --git a/examples/talon-docker/Dockerfile b/examples/talon-whatsapp/Dockerfile similarity index 94% rename from examples/talon-docker/Dockerfile rename to examples/talon-whatsapp/Dockerfile index e24b61b2f3b..a167a2708ab 100644 --- a/examples/talon-docker/Dockerfile +++ b/examples/talon-whatsapp/Dockerfile @@ -48,7 +48,7 @@ WORKDIR /opt/deepagents-src COPY libs/deepagents ./libs/deepagents COPY libs/code ./libs/code COPY libs/talon ./libs/talon -COPY examples/talon-docker/AGENTS.md /opt/deepagents-talon/AGENTS.md +COPY examples/talon-whatsapp/AGENTS.md /opt/deepagents-talon/AGENTS.md RUN mkdir -p /opt/whatsapp-bridge && \ cp libs/talon/deepagents_talon/channels/whatsapp_bridge/package.json \ @@ -60,4 +60,4 @@ RUN cd libs/talon && uv sync --frozen --extra speech WORKDIR /workspace -CMD ["/opt/deepagents-talon-venv/bin/deepagents-talon"] +CMD ["/opt/deepagents-talon-venv/bin/deepagents-talon", "--whatsapp"] diff --git a/examples/talon-whatsapp/README.md b/examples/talon-whatsapp/README.md new file mode 100644 index 00000000000..3ef5db494d2 --- /dev/null +++ b/examples/talon-whatsapp/README.md @@ -0,0 +1,62 @@ +# Talon WhatsApp Example + +This example runs one Talon host process with the WhatsApp bridge subprocess in the same container. The bridge binds to loopback inside the container and the host `~/agent-workspace/` directory is mounted at `/workspace`. + +> **Experimental:** Talon is an experimental runtime and is subject to change or removal at any time. + +## Run + +```bash +cp .env.example .env +mkdir -p ~/agent-workspace +# Fill AGENT_MODEL provider credentials, then build once and run: +docker compose build +docker compose up +``` + +Scan the QR code printed by the bridge. The default exposure mode is `self`, so only messages sent by the paired WhatsApp account trigger the agent. Use `allowlist` or `open` only when you intentionally want other chats to trigger the agent. + +Voice transcription is enabled in `.env.example`. The Docker example installs `ffmpeg` and the Talon `speech` extra so inbound WhatsApp voice notes are transcribed locally with NVIDIA Parakeet through Transformers before reaching the agent. The first voice message can be slow because the ASR model is downloaded lazily. Set `DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_DEVICE=cuda` when running on a GPU-enabled host. + +Cron records, downloaded inbound media, and WhatsApp session state persist under `~/agent-workspace/.deepagents/`. The agent's default working directory is `/workspace`, so files it creates are written into `~/agent-workspace/` on the host. + +The image installs the Talon package at build time. Rebuild after changing the Dockerfile, system packages, Node dependencies, or Talon Python dependencies. + +## Local Run Without Docker + +```bash +cp .env.example .env +set -a +. ./.env +set +a + +cd ../../libs/talon/deepagents_talon/channels/whatsapp_bridge +npm install + +cd ../../../.. +uv sync --directory libs/talon --extra speech +cp examples/talon-whatsapp/AGENTS.md ~/.deepagents/whatsapp-local/agent/AGENTS.md +export DEEPAGENTS_TALON_WORKSPACE=~/agent-workspace +uv run --directory libs/talon deepagents-talon --whatsapp +``` + +## Environment Reference + +`AGENT_ASSISTANT_ID` names the local state directory under `~/.deepagents/`. `AGENT_MODEL` selects the Deep Agents chat model. If it is unset, Talon runs the echo runtime for smoke tests. + +The Docker example overrides `DEEPAGENTS_TALON_HOME` to `/workspace/.deepagents`, so cron jobs are stored at `~/agent-workspace/.deepagents//cron/jobs.json`. Assistant Markdown image/video attachments must use relative paths inside `DEEPAGENTS_TALON_OUTBOUND_MEDIA_DIR`, or inside `DEEPAGENTS_TALON_WORKSPACE` when no outbound media directory is configured. + +Set `LANGSMITH_TRACING=true` and `LANGSMITH_API_KEY` to trace each channel or cron-triggered run. `LANGSMITH_PROJECT` defaults to `deepagents-talon`. + +WhatsApp exposure: + +- `DEEPAGENTS_TALON_WHATSAPP_EXPOSURE=self` allows only messages from the paired account. +- `DEEPAGENTS_TALON_WHATSAPP_EXPOSURE=allowlist` allows chats in `DEEPAGENTS_TALON_WHATSAPP_ALLOWLIST_CHATS` or messages matching `DEEPAGENTS_TALON_WHATSAPP_MENTION_PATTERNS`. +- `DEEPAGENTS_TALON_WHATSAPP_EXPOSURE=open` allows every inbound WhatsApp message. + +Cron jobs are stored in the assistant state directory at `cron/jobs.json`. Scheduler ticks, dispatch, success/failure, and delivery outcomes are logged as `talon_event` JSON records. + +## Resources + +- [LangChain Academy](https://academy.langchain.com/) — Comprehensive, free courses on LangChain libraries and products, made by the LangChain team. +- [Code of Conduct](https://github.com/langchain-ai/langchain/?tab=coc-ov-file) — community guidelines and standards diff --git a/examples/talon-docker/docker-compose.yml b/examples/talon-whatsapp/docker-compose.yml similarity index 57% rename from examples/talon-docker/docker-compose.yml rename to examples/talon-whatsapp/docker-compose.yml index b4d812c360d..73d09d6ed2d 100644 --- a/examples/talon-docker/docker-compose.yml +++ b/examples/talon-whatsapp/docker-compose.yml @@ -2,8 +2,8 @@ services: talon: build: context: ../.. - dockerfile: examples/talon-docker/Dockerfile - image: deepagents-talon:local + dockerfile: examples/talon-whatsapp/Dockerfile + image: deepagents-talon-whatsapp:local working_dir: /workspace env_file: - .env @@ -11,15 +11,13 @@ services: DEEPAGENTS_TALON_HOME: /workspace/.deepagents DEEPAGENTS_TALON_WORKSPACE: /workspace DEEPAGENTS_TALON_WHATSAPP_SESSION_DIR: /workspace/.deepagents/whatsapp-session - DEEPAGENTS_TALON_TELEGRAM_SESSION_DIR: /workspace/.deepagents/telegram-session DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_ENABLED: ${DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_ENABLED:-true} DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_DEVICE: ${DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_DEVICE:-cpu} volumes: - ${HOME}/agent-workspace:/workspace command: > bash -c " - assistant_id=\"$${AGENT_ASSISTANT_ID:-default}\" && - mkdir -p \"/workspace/.deepagents/$${assistant_id}/agent\" && - cp /opt/deepagents-talon/AGENTS.md \"/workspace/.deepagents/$${assistant_id}/agent/AGENTS.md\" && - exec /opt/deepagents-talon-venv/bin/deepagents-talon + mkdir -p /workspace/.deepagents/$${AGENT_ASSISTANT_ID}/agent && + cp /opt/deepagents-talon/AGENTS.md /workspace/.deepagents/$${AGENT_ASSISTANT_ID}/agent/AGENTS.md && + /opt/deepagents-talon-venv/bin/deepagents-talon --whatsapp " diff --git a/libs/talon/README.md b/libs/talon/README.md index eb4e79c61da..6ca286969d4 100644 --- a/libs/talon/README.md +++ b/libs/talon/README.md @@ -62,7 +62,7 @@ cd ../../.. DEEPAGENTS_TALON_WHATSAPP_ENABLED=true \ DEEPAGENTS_TALON_WHATSAPP_START_BRIDGE=true \ -AGENT_ASSISTANT_ID=talon-docker-local \ +AGENT_ASSISTANT_ID=whatsapp-local \ AGENT_MODEL=: \ uv run deepagents-talon --whatsapp ``` @@ -84,7 +84,7 @@ DEEPAGENTS_TALON_WHATSAPP_EXPOSURE=open DEEPAGENTS_TALON_WHATSAPP_OPEN_ACK=allow-arbitrary-senders ``` -See `../../examples/talon-docker/` for a runnable Docker Compose topology and `.env` reference. +See `../../examples/talon-whatsapp/` for a runnable Docker Compose topology and `.env` reference. ## Telegram diff --git a/libs/talon/tests/channels/test_telegram.py b/libs/talon/tests/channels/test_telegram.py index 497449d6f06..82250d17876 100644 --- a/libs/talon/tests/channels/test_telegram.py +++ b/libs/talon/tests/channels/test_telegram.py @@ -4,7 +4,7 @@ import json import os from pathlib import Path -from typing import Self, cast +from typing import Literal, Self, cast import pytest @@ -175,6 +175,28 @@ def download( monkeypatch.setattr(telegram_module, "_download_file", download) +async def _run_channel_once( + channel: TelegramChannel, + *, + expected_messages: int = 1, +) -> list[ChannelMessage]: + received: list[ChannelMessage] = [] + + async def record(message: ChannelMessage) -> None: + received.append(message) + + channel.set_message_handler(record) + await channel.start() + try: + if expected_messages: + await _wait_for_received(received, expected_messages) + else: + await asyncio.sleep(0) + finally: + await channel.stop() + return received + + # --- Config tests --- @@ -573,39 +595,37 @@ async def test_send_message_chunks_long_text(tmp_path: Path) -> None: # --- Outbound media tests --- -async def test_send_media_sends_photo_for_images(tmp_path: Path) -> None: - transport = RecordingTransport() - image = tmp_path / "image.png" - image.write_bytes(b"image-data") - channel = TelegramChannel( - _make_config(tmp_path), - transport=cast("TelegramTransport", transport), - ) - - await channel.send_media("123", ChannelMedia(path=image, media_type="image", caption="cap")) - - assert transport.uploads == [ +async def test_send_media_uses_expected_upload_method(tmp_path: Path) -> None: + cases: tuple[ + tuple[str, Literal["image", "video"], str | None, str, str, dict[str, object]], + ..., + ] = ( ( + "image.png", + "image", + "cap", "sendPhoto", "photo", - image, {"chat_id": "123", "caption": "cap"}, ), - ] - - -async def test_send_media_sends_document_for_videos(tmp_path: Path) -> None: - transport = RecordingTransport() - video = tmp_path / "clip.mp4" - video.write_bytes(b"video-data") - channel = TelegramChannel( - _make_config(tmp_path), - transport=cast("TelegramTransport", transport), + ("clip.mp4", "video", None, "sendDocument", "document", {"chat_id": "123"}), ) - await channel.send_media("123", ChannelMedia(path=video, media_type="video")) + for filename, media_type, caption, method, file_field, params in cases: + transport = RecordingTransport() + path = tmp_path / filename + path.write_bytes(b"media-data") + channel = TelegramChannel( + _make_config(tmp_path), + transport=cast("TelegramTransport", transport), + ) + + await channel.send_media( + "123", + ChannelMedia(path=path, media_type=media_type, caption=caption), + ) - assert transport.uploads == [("sendDocument", "document", video, {"chat_id": "123"})] + assert transport.uploads == [(method, file_field, path, params)] async def test_send_media_sends_long_caption_as_text_before_upload(tmp_path: Path) -> None: @@ -680,32 +700,27 @@ def patched_stat( monkeypatch.setattr(os, "stat", patched_stat) -async def test_send_media_rejects_oversized_photo( +async def test_send_media_rejects_provider_oversized_files( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: - image = tmp_path / "big.png" - image.write_bytes(b"x") - channel = TelegramChannel(_make_config(tmp_path)) - - _patch_file_size(monkeypatch, image, MAX_PHOTO_BYTES + 1) - - with pytest.raises(ChannelMediaError, match="too large for Telegram"): - await channel.send_media("123", ChannelMedia(path=image, media_type="image")) - - -async def test_send_media_rejects_oversized_document( - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, -) -> None: - video = tmp_path / "big.mp4" - video.write_bytes(b"x") - channel = TelegramChannel(_make_config(tmp_path)) + cases: tuple[tuple[str, Literal["image", "video"], int], ...] = ( + ("big.png", "image", MAX_PHOTO_BYTES + 1), + ("big.mp4", "video", MAX_DOCUMENT_BYTES + 1), + ) - _patch_file_size(monkeypatch, video, MAX_DOCUMENT_BYTES + 1) + for filename, media_type, fake_size in cases: + path = tmp_path / filename + path.write_bytes(b"x") + channel = TelegramChannel(_make_config(tmp_path)) - with pytest.raises(ChannelMediaError, match="too large for Telegram"): - await channel.send_media("123", ChannelMedia(path=video, media_type="video")) + with monkeypatch.context() as patch: + _patch_file_size(patch, path, fake_size) + with pytest.raises(ChannelMediaError, match="too large for Telegram"): + await channel.send_media( + "123", + ChannelMedia(path=path, media_type=media_type), + ) # --- Edit message tests --- @@ -726,48 +741,18 @@ async def test_edit_message_uses_plain_text(tmp_path: Path) -> None: assert transport.calls[0][1]["message_id"] == 42 -# --- Typing indicator tests --- - - -async def test_send_typing_calls_send_chat_action(tmp_path: Path) -> None: - transport = RecordingTransport() - channel = TelegramChannel( - _make_config(tmp_path), - transport=cast("TelegramTransport", transport), - ) - - await channel.send_typing("123") - - assert transport.calls[0] == ("sendChatAction", {"chat_id": "123", "action": "typing"}) - - -async def test_send_typing_swallows_errors(tmp_path: Path) -> None: - class FailingTransport: - async def call(self, method: str, **params: object) -> object: # noqa: ARG002 # test fake - msg = "network error" - raise TelegramError(msg) - - channel = TelegramChannel( - _make_config(tmp_path), - transport=cast("TelegramTransport", FailingTransport()), - ) - - # Should not raise. - await channel.send_typing("123") - - # --- Inbound media parsing tests --- -async def test_channel_parses_inbound_photo( +async def test_channel_parses_inbound_media( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: _stub_download(monkeypatch) - transport = RecordingTransport( - updates=[ + cases: tuple[tuple[str, dict[str, object], dict[str, object]], ...] = ( + ( + "photo", _make_update( - update_id=1, chat_id=111, sender_id=111, text="", @@ -776,82 +761,26 @@ async def test_channel_parses_inbound_photo( {"file_id": "large", "file_size": 500}, ], ), - ], - ) - channel = TelegramChannel( - _make_config(tmp_path, operator_id="111"), - transport=cast("TelegramTransport", transport), - ) - received: list[ChannelMessage] = [] - - async def record(message: ChannelMessage) -> None: - received.append(message) - - channel.set_message_handler(record) - - await channel.start() - await _wait_for_received(received, 1) - await channel.stop() - - assert received[0].metadata["media_type"] == "image" - assert received[0].metadata["file_id"] == "large" - assert received[0].metadata["media_paths"] == [ - str(tmp_path / "telegram" / "media" / "10_large.jpg"), - ] - assert received[0].metadata["media_path"] == str( - tmp_path / "telegram" / "media" / "10_large.jpg", - ) - media_path = Path(cast("str", received[0].metadata["media_path"])) - assert await asyncio.to_thread(media_path.read_bytes) == b"media-bytes" - - -async def test_channel_parses_inbound_voice( - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, -) -> None: - _stub_download(monkeypatch) - transport = RecordingTransport( - updates=[ + {"media_type": "image", "file_id": "large", "suffix": ".jpg"}, + ), + ( + "voice", _make_update( - update_id=1, chat_id=111, sender_id=111, text="", voice={"file_id": "voice123", "duration": 5}, ), - ], - ) - channel = TelegramChannel( - _make_config(tmp_path, operator_id="111"), - transport=cast("TelegramTransport", transport), - ) - received: list[ChannelMessage] = [] - - async def record(message: ChannelMessage) -> None: - received.append(message) - - channel.set_message_handler(record) - - await channel.start() - await _wait_for_received(received, 1) - await channel.stop() - - assert received[0].metadata["media_type"] == "voice" - assert received[0].metadata["file_id"] == "voice123" - assert received[0].metadata["voice_path"] == str( - tmp_path / "telegram" / "media" / "10_voice123.ogg", - ) - - -async def test_channel_parses_inbound_document( - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, -) -> None: - _stub_download(monkeypatch) - transport = RecordingTransport( - updates=[ + { + "media_type": "voice", + "file_id": "voice123", + "suffix": ".ogg", + "voice_path": True, + }, + ), + ( + "document", _make_update( - update_id=1, chat_id=111, sender_id=111, text="", @@ -861,30 +790,41 @@ async def test_channel_parses_inbound_document( "mime_type": "application/pdf", }, ), - ], - ) - channel = TelegramChannel( - _make_config(tmp_path, operator_id="111"), - transport=cast("TelegramTransport", transport), + { + "media_type": "document", + "file_id": "doc123", + "file_name": "report.pdf", + "media_mime_types": ["application/pdf"], + "suffix": ".pdf", + }, + ), ) - received: list[ChannelMessage] = [] - - async def record(message: ChannelMessage) -> None: - received.append(message) - - channel.set_message_handler(record) - await channel.start() - await _wait_for_received(received, 1) - await channel.stop() - - assert received[0].metadata["media_type"] == "document" - assert received[0].metadata["file_id"] == "doc123" - assert received[0].metadata["file_name"] == "report.pdf" - assert received[0].metadata["media_mime_types"] == ["application/pdf"] - assert received[0].metadata["media_paths"] == [ - str(tmp_path / "telegram" / "media" / "10_doc123.pdf"), - ] + for name, update, expected in cases: + case_dir = tmp_path / name + transport = RecordingTransport(updates=[update]) + channel = TelegramChannel( + _make_config(case_dir, operator_id="111"), + transport=cast("TelegramTransport", transport), + ) + + received = await _run_channel_once(channel) + metadata = received[0].metadata + file_id = cast("str", expected["file_id"]) + expected_path = str(case_dir / "telegram" / "media" / f"10_{file_id}{expected['suffix']}") + + assert metadata["media_type"] == expected["media_type"] + assert metadata["file_id"] == file_id + assert metadata["media_paths"] == [expected_path] + assert metadata["media_path"] == expected_path + if "file_name" in expected: + assert metadata["file_name"] == expected["file_name"] + if "media_mime_types" in expected: + assert metadata["media_mime_types"] == expected["media_mime_types"] + if expected.get("voice_path") is True: + assert metadata["voice_path"] == expected_path + media_path = Path(cast("str", metadata["media_path"])) + assert await asyncio.to_thread(media_path.read_bytes) == b"media-bytes" async def test_channel_skips_oversized_inbound_media_from_get_file( @@ -978,73 +918,33 @@ def fake_urlopen(request: object, *, timeout: float) -> ChunkedResponse: # noqa assert not destination.exists() -# --- Status tests --- - - -async def test_status_reports_disconnected_before_start(tmp_path: Path) -> None: - channel = TelegramChannel(_make_config(tmp_path)) - - status = await channel.status() - - assert status.provider == "telegram" - assert status.connected is False - - -async def test_status_reports_connected_after_start(tmp_path: Path) -> None: - transport = RecordingTransport() - channel = TelegramChannel( - _make_config(tmp_path, exposure=ChannelExposure(mode=ExposureMode.OPEN)), - transport=cast("TelegramTransport", transport), - ) - - await channel.start() - await asyncio.sleep(0) - status = await channel.status() - await channel.stop() - - assert status.connected is True - - # --- Offset persistence tests (ticket 23) --- -def test_offset_round_trip(tmp_path: Path) -> None: +def test_offset_round_trip_uses_atomic_file_replace(tmp_path: Path) -> None: offset_file = tmp_path / "telegram_offset.json" - _save_offset(offset_file, 42) + _save_offset(offset_file, 100) loaded = _load_offset(offset_file) - assert loaded == 42 - - -def test_offset_missing_file_returns_zero(tmp_path: Path) -> None: - assert _load_offset(tmp_path / "nonexistent.json") == 0 - - -def test_offset_corrupt_file_returns_zero(tmp_path: Path) -> None: - offset_file = tmp_path / "telegram_offset.json" - offset_file.write_text("not valid json {{{", encoding="utf-8") - - assert _load_offset(offset_file) == 0 - - -def test_offset_invalid_value_returns_zero(tmp_path: Path) -> None: - offset_file = tmp_path / "telegram_offset.json" - offset_file.write_text(json.dumps({"offset": -5}), encoding="utf-8") - - assert _load_offset(offset_file) == 0 - + assert loaded == 100 + assert offset_file.is_file() + assert not (tmp_path / "telegram_offset.json.tmp").exists() + assert json.loads(offset_file.read_text(encoding="utf-8")) == {"offset": 100} -def test_offset_atomic_write(tmp_path: Path) -> None: - offset_file = tmp_path / "telegram_offset.json" - _save_offset(offset_file, 100) +def test_offset_invalid_or_missing_file_returns_zero(tmp_path: Path) -> None: + cases: tuple[tuple[str, str | None], ...] = ( + ("missing.json", None), + ("corrupt.json", "not valid json {{{"), + ("invalid.json", json.dumps({"offset": -5})), + ) - # The temp file should have been replaced by the real file. - assert offset_file.is_file() - assert not (tmp_path / "telegram_offset.json.tmp").exists() - data = json.loads(offset_file.read_text(encoding="utf-8")) - assert data == {"offset": 100} + for filename, content in cases: + offset_file = tmp_path / filename + if content is not None: + offset_file.write_text(content, encoding="utf-8") + assert _load_offset(offset_file) == 0 async def test_channel_persists_offset_after_polling(tmp_path: Path) -> None: diff --git a/libs/talon/tests/integration_tests/test_telegram_host.py b/libs/talon/tests/integration_tests/test_telegram_host.py index 211b79b0d76..2b49e1c2348 100644 --- a/libs/talon/tests/integration_tests/test_telegram_host.py +++ b/libs/talon/tests/integration_tests/test_telegram_host.py @@ -66,81 +66,51 @@ async def invoke(self, request: AgentRequest) -> AgentResult: return AgentResult(text=f"reply:{request.text}") -def test_channels_factory_returns_both_when_both_enabled(tmp_path: Path) -> None: - config = TalonConfig.from_env( - { - "AGENT_ASSISTANT_ID": "assistant", - "DEEPAGENTS_TALON_WHATSAPP_ENABLED": "1", - "DEEPAGENTS_TALON_TELEGRAM_ENABLED": "1", - "DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN": "test-token", - "DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID": "999", - }, - base_home=tmp_path, +def test_channels_factory_selects_configured_channels(tmp_path: Path) -> None: + cases: tuple[tuple[dict[str, str], bool, bool, tuple[type[object], ...]], ...] = ( + ( + { + "DEEPAGENTS_TALON_WHATSAPP_ENABLED": "1", + "DEEPAGENTS_TALON_TELEGRAM_ENABLED": "1", + "DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN": "test-token", + "DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID": "999", + }, + False, + False, + (WhatsAppChannel, TelegramChannel), + ), + ( + { + "DEEPAGENTS_TALON_TELEGRAM_ENABLED": "1", + "DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN": "test-token", + "DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID": "999", + }, + False, + False, + (TelegramChannel,), + ), + ({"DEEPAGENTS_TALON_WHATSAPP_ENABLED": "1"}, False, False, (WhatsAppChannel,)), + ({}, False, False, ()), + ( + { + "DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN": "test-token", + "DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID": "999", + }, + True, + True, + (WhatsAppChannel, TelegramChannel), + ), ) - channels = _channels(config, whatsapp=False, telegram=False) - - assert len(channels) == 2 - assert isinstance(channels[0], WhatsAppChannel) - assert isinstance(channels[1], TelegramChannel) - + for env, whatsapp, telegram, expected_types in cases: + config = TalonConfig.from_env( + {"AGENT_ASSISTANT_ID": "assistant", **env}, + base_home=tmp_path, + ) -def test_channels_factory_returns_only_telegram(tmp_path: Path) -> None: - config = TalonConfig.from_env( - { - "AGENT_ASSISTANT_ID": "assistant", - "DEEPAGENTS_TALON_TELEGRAM_ENABLED": "1", - "DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN": "test-token", - "DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID": "999", - }, - base_home=tmp_path, - ) + channels = _channels(config, whatsapp=whatsapp, telegram=telegram) - channels = _channels(config, whatsapp=False, telegram=False) - - assert len(channels) == 1 - assert isinstance(channels[0], TelegramChannel) - - -def test_channels_factory_returns_only_whatsapp(tmp_path: Path) -> None: - config = TalonConfig.from_env( - { - "AGENT_ASSISTANT_ID": "assistant", - "DEEPAGENTS_TALON_WHATSAPP_ENABLED": "1", - }, - base_home=tmp_path, - ) - - channels = _channels(config, whatsapp=False, telegram=False) - - assert len(channels) == 1 - assert isinstance(channels[0], WhatsAppChannel) - - -def test_channels_factory_returns_neither(tmp_path: Path) -> None: - config = TalonConfig.from_env( - {"AGENT_ASSISTANT_ID": "assistant"}, - base_home=tmp_path, - ) - - channels = _channels(config, whatsapp=False, telegram=False) - - assert channels == () - - -def test_channels_factory_accepts_cli_flags(tmp_path: Path) -> None: - config = TalonConfig.from_env( - { - "AGENT_ASSISTANT_ID": "assistant", - "DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN": "test-token", - "DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID": "999", - }, - base_home=tmp_path, - ) - - channels = _channels(config, whatsapp=True, telegram=True) - - assert len(channels) == 2 + assert tuple(type(channel) for channel in channels) == expected_types async def test_simultaneous_channels_coexist_without_interference(tmp_path: Path) -> None: @@ -174,28 +144,6 @@ async def test_simultaneous_channels_coexist_without_interference(tmp_path: Path assert agent.requests[1].metadata["channel"] == "telegram" -async def test_stop_command_cancels_per_channel(tmp_path: Path) -> None: - whatsapp_channel = RecordingChannel("whatsapp") - telegram_channel = RecordingChannel("telegram") - agent = EchoAgent() - config = TalonConfig.from_env( - {"AGENT_ASSISTANT_ID": "assistant"}, - base_home=tmp_path, - ) - host = TalonHost( - config=config, - agent=agent, - channels=[whatsapp_channel, telegram_channel], - ) - - await host.start() - await whatsapp_channel.receive("/stop", conversation_id="wa-chat") - await _drain() - await host.stop() - - assert len(agent.requests) == 0 - - async def _drain() -> None: for _ in range(100): await asyncio.sleep(0) From 9e77d996846b16902101cc55b1dd2799de192122 Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sat, 20 Jun 2026 18:55:44 -0700 Subject: [PATCH 15/48] fix(talon): normalize Telegram voice suffixes --- libs/talon/deepagents_talon/channels/telegram.py | 2 ++ libs/talon/tests/channels/test_telegram.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/libs/talon/deepagents_talon/channels/telegram.py b/libs/talon/deepagents_talon/channels/telegram.py index 5ea42a2a519..cf7812a5739 100644 --- a/libs/talon/deepagents_talon/channels/telegram.py +++ b/libs/talon/deepagents_talon/channels/telegram.py @@ -745,6 +745,8 @@ def _downloaded_mime_type(path: Path, metadata: dict[str, object]) -> str | None def _safe_suffix(file_path: str, media_type: str) -> str: suffix = Path(file_path).suffix.lower() + if media_type == "voice" and suffix in {".oga", ".opus"}: + return ".ogg" if re.fullmatch(r"\.[a-z0-9]{1,16}", suffix): return suffix return _default_suffix(media_type) diff --git a/libs/talon/tests/channels/test_telegram.py b/libs/talon/tests/channels/test_telegram.py index 82250d17876..13c4af5f7a9 100644 --- a/libs/talon/tests/channels/test_telegram.py +++ b/libs/talon/tests/channels/test_telegram.py @@ -59,7 +59,7 @@ async def call(self, method: str, **params: object) -> object: if method == "getFile": file_id = params.get("file_id") if file_id == "voice123": - file_path = "voice/file.ogg" + file_path = "voice/file.oga" elif file_id == "doc123": file_path = "documents/report.pdf" else: From 4eca0b76bcb4cb5a853e597d46c8c1146e26bcf0 Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sun, 21 Jun 2026 11:42:53 -0700 Subject: [PATCH 16/48] refactor(talon): reduce duplicate code across channel adapters MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Address code review feedback on PR #4097: - Unify / via shared - Remove redundant — callers already validate - Move to and import from both adapters - Centralize open-exposure warning in , eliminating provider-specific wrappers - Convert from stored field to computed returning - Simplify using with a key function - Reuse in instead of reimplementing the size check - Inline trivial property and one-liner - Extract helper in for duplicated truthy-set - Fix tmp file path to use + suffix - Document intentional behavior in docstring - Extract shared helper for identical methods - Consolidate test into shared --- libs/talon/deepagents_talon/__main__.py | 25 +-- libs/talon/deepagents_talon/channels/base.py | 68 +++++-- .../deepagents_talon/channels/telegram.py | 170 +++++++----------- .../deepagents_talon/channels/whatsapp.py | 58 ++---- libs/talon/tests/channels/test_base.py | 7 +- libs/talon/tests/channels/test_telegram.py | 13 +- libs/talon/tests/channels/test_whatsapp.py | 7 +- libs/talon/tests/conftest.py | 54 ++++++ .../integration_tests/test_telegram_host.py | 40 +---- libs/talon/tests/test_host.py | 34 +--- 10 files changed, 224 insertions(+), 252 deletions(-) create mode 100644 libs/talon/tests/conftest.py diff --git a/libs/talon/deepagents_talon/__main__.py b/libs/talon/deepagents_talon/__main__.py index 7ae24109069..97b4a31a6a1 100644 --- a/libs/talon/deepagents_talon/__main__.py +++ b/libs/talon/deepagents_talon/__main__.py @@ -199,21 +199,26 @@ def _channels( telegram: bool = False, ) -> tuple[ChannelAdapter, ...]: channels: list[ChannelAdapter] = [] - if whatsapp or config.env.get("DEEPAGENTS_TALON_WHATSAPP_ENABLED", "").lower() in { - "1", - "true", - "yes", - }: + if whatsapp or _env_enabled(config.env, "DEEPAGENTS_TALON_WHATSAPP_ENABLED"): channels.append(WhatsAppChannel(WhatsAppChannelConfig.from_talon_config(config))) - if telegram or config.env.get("DEEPAGENTS_TALON_TELEGRAM_ENABLED", "").lower() in { - "1", - "true", - "yes", - }: + if telegram or _env_enabled(config.env, "DEEPAGENTS_TALON_TELEGRAM_ENABLED"): channels.append(TelegramChannel(TelegramChannelConfig.from_talon_config(config))) return tuple(channels) +def _env_enabled(env: dict[str, str], key: str) -> bool: + """Check whether a boolean environment flag is truthy. + + Args: + env: Environment variable mapping. + key: Environment variable name. + + Returns: + `True` when the value is one of ``1``, ``true``, or ``yes``. + """ + return env.get(key, "").lower() in {"1", "true", "yes"} + + def _runtime_env(config: TalonConfig) -> dict[str, str]: values = dict(os.environ) values.update(config.env) diff --git a/libs/talon/deepagents_talon/channels/base.py b/libs/talon/deepagents_talon/channels/base.py index 7bd446e27d6..a4dbd94a0da 100644 --- a/libs/talon/deepagents_talon/channels/base.py +++ b/libs/talon/deepagents_talon/channels/base.py @@ -6,6 +6,7 @@ from __future__ import annotations import fnmatch +import logging import mimetypes import re from dataclasses import dataclass, field @@ -13,7 +14,7 @@ from pathlib import Path from typing import TYPE_CHECKING -from deepagents_talon.interfaces import ChannelMedia, ChannelMessage +from deepagents_talon.interfaces import ChannelMedia, ChannelMessage, MessageHandler from deepagents_talon.media import resolve_bounded_media_path if TYPE_CHECKING: @@ -31,6 +32,8 @@ _BOLD_PATTERN = re.compile(r"\*\*([^*]+)\*\*|__([^_]+)__") _ITALIC_PATTERN = re.compile(r"(? None: - """Normalize the legacy single-operator field into the operator id set.""" - operator_ids = set(self.operator_ids) - if self.operator_id is not None: - operator_ids.add(self.operator_id) - object.__setattr__(self, "operator_ids", frozenset(operator_ids)) + @property + def operator_id(self) -> str | None: + """First operator id, or ``None`` when no operators are configured.""" + return next(iter(self.operator_ids), None) def allows(self, message: ChannelMessage) -> bool: """Return whether an inbound message may trigger the agent. @@ -196,8 +194,7 @@ def channel_exposure_from_env( env.get(config.exposure, ExposureMode.SELF.value), provider=config.provider, ) - operator_ids = tuple(split_csv(env.get(config.operator_id, ""))) - operator_id = operator_ids[0] if operator_ids else None + operator_ids = frozenset(split_csv(env.get(config.operator_id, ""))) if mode == ExposureMode.SELF and config.require_self_operator and not operator_ids: msg = ( f"{config.provider} self exposure requires {config.operator_id}; " @@ -206,12 +203,16 @@ def channel_exposure_from_env( raise ValueError(msg) if mode == ExposureMode.OPEN: _require_open_acknowledgement(env, config) + logger.warning( + "%s open exposure enabled; arbitrary senders can trigger the agent with " + "operator credentials and local host access", + config.provider, + ) return ChannelExposure( mode=mode, - operator_id=operator_id, conversations=frozenset(split_csv(env.get(config.allowlist_chats, ""))), mention_patterns=tuple(split_csv(env.get(config.mention_patterns, ""))), - operator_ids=frozenset(operator_ids), + operator_ids=operator_ids, ) @@ -321,6 +322,12 @@ def filter_capped_media_paths( Returns: Filter result containing kept paths and dropped-path reasons. + + Note: + Paths that do not exist on disk are silently kept. This is intentional: + WhatsApp bridge downloads may still be in progress when inbound messages + are polled, so a missing file does not indicate an oversized or invalid + download — only one that has not landed yet. """ kept: list[str] = [] kept_mime_types: list[str] = [] @@ -450,6 +457,18 @@ def split_csv(value: str) -> list[str]: return [item.strip() for item in value.split(",") if item.strip()] +def optional_str(value: object) -> str | None: + """Return a non-empty string value, or ``None``. + + Args: + value: Raw value that may be a string. + + Returns: + The string if it is a non-empty ``str``, otherwise ``None``. + """ + return value if isinstance(value, str) and value else None + + def _validate_media_size( media: ChannelMedia, *, @@ -477,6 +496,25 @@ def _matches_text(text: str, patterns: tuple[str, ...]) -> bool: return any(fnmatch.fnmatchcase(text, pattern) for pattern in patterns) +async def dispatch_message( + handler: MessageHandler | None, + message: ChannelMessage, + *, + provider: str, +) -> None: + """Forward an inbound message to the registered handler. + + Args: + handler: Host callback for inbound messages, or ``None``. + message: Accepted inbound channel message. + provider: Provider name used in the drop warning when no handler is set. + """ + if handler is None: + logger.warning("Dropping %s message because no handler is registered", provider) + return + await handler(message) + + def _exposure_mode(value: str, *, provider: str) -> ExposureMode: try: return ExposureMode(value) diff --git a/libs/talon/deepagents_talon/channels/telegram.py b/libs/talon/deepagents_talon/channels/telegram.py index cf7812a5739..ef598bf0a14 100644 --- a/libs/talon/deepagents_talon/channels/telegram.py +++ b/libs/talon/deepagents_talon/channels/telegram.py @@ -26,12 +26,15 @@ ExposureMode, channel_exposure_from_env, chunk_text, + dispatch_message, max_media_bytes_from_env, message_with_media_paths, + optional_str, parse_float, replace_message_metadata, split_csv, validate_media, + validate_media_size, ) from deepagents_talon.interfaces import ChannelMedia, ChannelMessage, ChannelStatus, MessageHandler @@ -138,7 +141,18 @@ def from_talon_config(cls, config: TalonConfig) -> TelegramChannelConfig: or env.get("DEEPAGENTS_TALON_WORKSPACE") or "/workspace", ) - exposure = _exposure_from_env(env) + exposure = channel_exposure_from_env( + env, + ChannelExposureEnv( + provider="Telegram", + exposure="DEEPAGENTS_TALON_TELEGRAM_EXPOSURE", + allowlist_chats="DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_CHATS", + mention_patterns="DEEPAGENTS_TALON_TELEGRAM_MENTION_PATTERNS", + operator_id="DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID", + open_ack=OPEN_EXPOSURE_ACK_ENV, + require_self_operator=True, + ), + ) return cls( bot_token=token, session_dir=session, @@ -272,7 +286,7 @@ def _send_request(self, method: str, request: urllib.request.Request) -> object: except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as error: msg = f"Telegram Bot API request failed: {method}" raise TelegramError(msg) from error - return _raise_for_api_error(method, payload) + return payload class TelegramChannel: @@ -511,10 +525,7 @@ def _commit_update_offset(self, update: Mapping[str, object]) -> None: _save_offset(self.config.offset_file, self._offset) async def _dispatch(self, message: ChannelMessage) -> None: - if self._handler is None: - logger.warning("Dropping Telegram message because no handler is registered") - return - await self._handler(message) + await dispatch_message(self._handler, message, provider="Telegram") async def _prepare_inbound_media(self, message: ChannelMessage) -> ChannelMessage: media_type = message.metadata.get("media_type") @@ -594,16 +605,11 @@ async def _download_inbound_media( _download_file, download_url, destination, - self.timeout, + self.config.request_timeout_seconds, self.config.max_media_bytes, ) return destination - @property - def timeout(self) -> float: - """Request timeout for downloads.""" - return self.config.request_timeout_seconds - def _check_telegram_size(media: ChannelMedia) -> None: """Validate media size against Telegram-specific limits. @@ -614,21 +620,14 @@ def _check_telegram_size(media: ChannelMedia) -> None: Raises: ChannelMediaError: If the file exceeds Telegram's size limit. """ - size = media.path.stat().st_size - if media.media_type == "image" and size > MAX_PHOTO_BYTES: - msg = f"photo media is too large for Telegram: {size} bytes exceeds {MAX_PHOTO_BYTES}" - raise ChannelMediaError(msg) - if media.media_type != "image" and size > MAX_DOCUMENT_BYTES: - msg = f"document media is too large for Telegram: {size} bytes exceeds {MAX_DOCUMENT_BYTES}" - raise ChannelMediaError(msg) - - -def _raise_for_api_error(method: str, payload: object) -> object: - if isinstance(payload, dict) and not cast("Mapping[str, object]", payload).get("ok", True): - description = cast("Mapping[str, object]", payload).get("description", "unknown error") - msg = f"Telegram Bot API error in {method}: {description}" - raise TelegramError(msg) - return payload + limit = MAX_PHOTO_BYTES if media.media_type == "image" else MAX_DOCUMENT_BYTES + try: + validate_media_size(media.path, max_bytes=limit) + except ChannelMediaError: + size = media.path.stat().st_size + label = "photo" if media.media_type == "image" else "document" + msg = f"{label} media is too large for Telegram: {size} bytes exceeds {limit}" + raise ChannelMediaError(msg) from None def _encode_multipart_form( @@ -698,14 +697,9 @@ def _effective_exposure( exposure: ChannelExposure, operator_id: str | None, ) -> ChannelExposure: - if ( - exposure.mode != ExposureMode.SELF - or exposure.operator_id is not None - or exposure.operator_ids - or operator_id is None - ): + if exposure.mode != ExposureMode.SELF or exposure.operator_ids or operator_id is None: return exposure - return replace(exposure, operator_id=operator_id) + return replace(exposure, operator_ids=frozenset({operator_id})) def _with_from_self(message: ChannelMessage, bot_id: str | None) -> ChannelMessage: @@ -775,17 +769,17 @@ def _safe_filename_part(value: str) -> str: return re.sub(r"[^A-Za-z0-9_.-]+", "_", value).strip("._") or "file" -def _extract_result(payload: object) -> dict[str, object]: - """Extract the ``result`` field from a Bot API response. +def _validate_response(payload: object) -> object: + """Validate a Bot API response envelope and return the raw ``result`` value. Args: payload: Full Bot API response. Returns: - The ``result`` object. + The ``result`` field from the response. Raises: - TelegramError: If the response is malformed. + TelegramError: If the response is not an object or reports an error. """ if not isinstance(payload, dict): msg = "Telegram Bot API response must be an object" @@ -795,7 +789,22 @@ def _extract_result(payload: object) -> dict[str, object]: description = values.get("description", "unknown error") msg = f"Telegram Bot API error: {description}" raise TelegramError(msg) - result = values.get("result") + return values.get("result") + + +def _extract_result(payload: object) -> dict[str, object]: + """Extract the ``result`` field from a Bot API response. + + Args: + payload: Full Bot API response. + + Returns: + The ``result`` object. + + Raises: + TelegramError: If the response is malformed. + """ + result = _validate_response(payload) if not isinstance(result, dict): msg = "Telegram Bot API response missing result" raise TelegramError(msg) @@ -814,15 +823,7 @@ def _extract_updates(payload: object) -> list[dict[str, object]]: Raises: TelegramError: If the response is malformed. """ - if not isinstance(payload, dict): - msg = "Telegram getUpdates response must be an object" - raise TelegramError(msg) - values = cast("Mapping[str, object]", payload) - if not values.get("ok", True): - description = values.get("description", "unknown error") - msg = f"Telegram getUpdates error: {description}" - raise TelegramError(msg) - result = values.get("result") + result = _validate_response(payload) if not isinstance(result, list): msg = "Telegram getUpdates result must be a list" raise TelegramError(msg) @@ -939,7 +940,7 @@ def _extract_media_info(msg: Mapping[str, object]) -> _TelegramMediaInfo | None: return _TelegramMediaInfo( media_type="voice", file_id=file_id, - mime_type=_optional_str(values.get("mime_type")), + mime_type=optional_str(values.get("mime_type")), ) if isinstance(document, dict): values = cast("Mapping[str, object]", document) @@ -948,16 +949,12 @@ def _extract_media_info(msg: Mapping[str, object]) -> _TelegramMediaInfo | None: return _TelegramMediaInfo( media_type="document", file_id=file_id, - file_name=_optional_str(values.get("file_name")), - mime_type=_optional_str(values.get("mime_type")), + file_name=optional_str(values.get("file_name")), + mime_type=optional_str(values.get("mime_type")), ) return None -def _optional_str(value: object) -> str | None: - return value if isinstance(value, str) and value else None - - def _largest_photo_file_id(photo_sizes: object) -> str | None: """Extract the file_id of the largest photo size from a photo array. @@ -969,25 +966,18 @@ def _largest_photo_file_id(photo_sizes: object) -> str | None: """ if not isinstance(photo_sizes, list): return None - best: dict[str, object] | None = None - for size in photo_sizes: - if not isinstance(size, dict): - continue - current = best - if current is None: - best = cast("dict[str, object]", size) - else: - current_size = current.get("file_size", 0) - new_size = cast("Mapping[str, object]", size).get("file_size", 0) - if ( - isinstance(new_size, int) - and isinstance(current_size, int) - and new_size > current_size - ): - best = cast("dict[str, object]", size) - if best is None: + sizes = [size for size in photo_sizes if isinstance(size, dict)] + if not sizes: return None - file_id = best.get("file_id") + best = max( + sizes, + key=lambda s: ( + cast("Mapping[str, object]", s).get("file_size", 0) + if isinstance(cast("Mapping[str, object]", s).get("file_size"), int) + else 0 + ), + ) + file_id = cast("Mapping[str, object]", best).get("file_id") return file_id if isinstance(file_id, str) else None @@ -1032,38 +1022,6 @@ def _download_file(url: str, destination: Path, timeout: float, max_bytes: int) destination.chmod(0o600) -def _exposure_from_env(env: Mapping[str, str]) -> ChannelExposure: - """Build ChannelExposure from Telegram-specific env vars. - - Args: - env: Environment variable mapping. - - Returns: - Exposure policy for the Telegram channel. - - Raises: - ValueError: If the exposure mode is invalid or open mode is not acknowledged. - """ - exposure = channel_exposure_from_env( - env, - ChannelExposureEnv( - provider="Telegram", - exposure="DEEPAGENTS_TALON_TELEGRAM_EXPOSURE", - allowlist_chats="DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_CHATS", - mention_patterns="DEEPAGENTS_TALON_TELEGRAM_MENTION_PATTERNS", - operator_id="DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID", - open_ack=OPEN_EXPOSURE_ACK_ENV, - require_self_operator=True, - ), - ) - if exposure.mode == ExposureMode.OPEN: - logger.warning( - "Telegram open exposure enabled; arbitrary senders can trigger the agent with " - "operator credentials and local host access", - ) - return exposure - - # --- Offset persistence (ticket 23) --- @@ -1099,7 +1057,7 @@ def _save_offset(offset_file: Path, offset: int) -> None: """ offset_file.parent.mkdir(mode=0o700, parents=True, exist_ok=True) content = json.dumps({"offset": offset}) - tmp = offset_file.with_suffix(".json.tmp") + tmp = offset_file.parent / f"{offset_file.name}.tmp" tmp.write_text(content, encoding="utf-8") tmp.chmod(0o600) tmp.replace(offset_file) diff --git a/libs/talon/deepagents_talon/channels/whatsapp.py b/libs/talon/deepagents_talon/channels/whatsapp.py index 88673d5702f..cb210e25b73 100644 --- a/libs/talon/deepagents_talon/channels/whatsapp.py +++ b/libs/talon/deepagents_talon/channels/whatsapp.py @@ -24,13 +24,14 @@ MAX_TEXT_CHARS, ChannelExposure, ChannelExposureEnv, - ExposureMode, channel_exposure_from_env, chunk_text, + dispatch_message, filter_capped_media_paths, format_markdown_for_channel, max_media_bytes_from_env, message_with_media_paths, + optional_str, parse_float, parse_int, replace_message_metadata, @@ -145,14 +146,24 @@ def from_talon_config(cls, config: TalonConfig) -> WhatsAppChannelConfig: outbound_media_dir=outbound_media_dir, host=host, port=port, - exposure=_exposure_from_env(env), + exposure=channel_exposure_from_env( + env, + ChannelExposureEnv( + provider="WhatsApp", + exposure="DEEPAGENTS_TALON_WHATSAPP_EXPOSURE", + allowlist_chats="DEEPAGENTS_TALON_WHATSAPP_ALLOWLIST_CHATS", + mention_patterns="DEEPAGENTS_TALON_WHATSAPP_MENTION_PATTERNS", + operator_id="DEEPAGENTS_TALON_WHATSAPP_OPERATOR_ID", + open_ack=OPEN_EXPOSURE_ACK_ENV, + ), + ), bot_header=env.get("DEEPAGENTS_TALON_WHATSAPP_BOT_HEADER", DEFAULT_BOT_HEADER), bridge_command=command, chrome_path=env.get("DEEPAGENTS_TALON_WHATSAPP_CHROME_PATH"), web_version_cache_url=env.get("DEEPAGENTS_TALON_WHATSAPP_WEB_VERSION_CACHE_URL"), bridge_token=env.get("DEEPAGENTS_TALON_WHATSAPP_BRIDGE_TOKEN") or secrets.token_hex(DEFAULT_BRIDGE_TOKEN_BYTES), - max_media_bytes=_whatsapp_max_media_bytes_from_env(env), + max_media_bytes=min(max_media_bytes_from_env(env), DEFAULT_WHATSAPP_MAX_MEDIA_BYTES), poll_interval_seconds=parse_float( env.get("DEEPAGENTS_TALON_WHATSAPP_POLL_SECONDS"), DEFAULT_POLL_INTERVAL_SECONDS, @@ -502,10 +513,7 @@ async def _stop_bridge_output_tasks(self) -> None: self._bridge_stderr = None async def _dispatch(self, message: ChannelMessage) -> None: - if self._handler is None: - logger.warning("Dropping WhatsApp message because no handler is registered") - return - await self._handler(message) + await dispatch_message(self._handler, message, provider="WhatsApp") async def _post_result(self, path: str, payload: Mapping[str, object]) -> object: response = await self._transport.post(path, payload) @@ -545,10 +553,6 @@ def _bridge_media_dir(config: WhatsAppChannelConfig) -> Path: return config.inbound_media_dir or config.session_dir.parent / "media" -def _whatsapp_max_media_bytes_from_env(env: Mapping[str, str]) -> int: - return min(max_media_bytes_from_env(env), DEFAULT_WHATSAPP_MAX_MEDIA_BYTES) - - def _stage_bridge_media(path: Path, config: WhatsAppChannelConfig) -> Path: media_dir = _bridge_media_dir(config).expanduser().resolve() source = path.expanduser().resolve() @@ -594,7 +598,7 @@ def _parse_message(payload: object) -> ChannelMessage: or values.get("mimeTypes") or values.get("media_types"), ) - message_type = _optional_str( + message_type = optional_str( values.get("message_type") or values.get("messageType") or values.get("mediaType"), ) media_type = _message_media_type(values, message_type, media_mime_types) @@ -604,8 +608,8 @@ def _parse_message(payload: object) -> ChannelMessage: return ChannelMessage( conversation_id=_required_str_any(values, ("chat_id", "chatId")), text=text if isinstance(text, str) else "", - sender_id=_optional_str(values.get("user_id") or values.get("senderId")), - message_id=_optional_str(values.get("message_id") or values.get("messageId")), + sender_id=optional_str(values.get("user_id") or values.get("senderId")), + message_id=optional_str(values.get("message_id") or values.get("messageId")), metadata={ "provider": "whatsapp", "message_type": message_type, @@ -688,10 +692,6 @@ def _required_str_any(payload: Mapping[str, object], keys: tuple[str, ...]) -> s raise WhatsAppBridgeError(msg) -def _optional_str(value: object) -> str | None: - return value if isinstance(value, str) and value else None - - def _str_list(value: object) -> list[str]: if not isinstance(value, list): return [] @@ -703,7 +703,7 @@ def _message_media_type( message_type: str | None, media_mime_types: list[str], ) -> str | None: - raw = _optional_str(values.get("media_type") or values.get("mediaType")) + raw = optional_str(values.get("media_type") or values.get("mediaType")) candidates = [raw, message_type, *media_mime_types] if any(_is_voice_type(candidate) for candidate in candidates): return "voice" @@ -732,26 +732,6 @@ def _is_video_type(value: str | None) -> bool: return isinstance(value, str) and "video" in value.lower() -def _exposure_from_env(env: Mapping[str, str]) -> ChannelExposure: - exposure = channel_exposure_from_env( - env, - ChannelExposureEnv( - provider="WhatsApp", - exposure="DEEPAGENTS_TALON_WHATSAPP_EXPOSURE", - allowlist_chats="DEEPAGENTS_TALON_WHATSAPP_ALLOWLIST_CHATS", - mention_patterns="DEEPAGENTS_TALON_WHATSAPP_MENTION_PATTERNS", - operator_id="DEEPAGENTS_TALON_WHATSAPP_OPERATOR_ID", - open_ack=OPEN_EXPOSURE_ACK_ENV, - ), - ) - if exposure.mode == ExposureMode.OPEN: - logger.warning( - "WhatsApp open exposure enabled; arbitrary senders can trigger the agent with " - "operator credentials and local host access" - ) - return exposure - - def _bridge_command(env: Mapping[str, str]) -> tuple[str, ...] | None: value = env.get("DEEPAGENTS_TALON_WHATSAPP_BRIDGE_COMMAND") if value: diff --git a/libs/talon/tests/channels/test_base.py b/libs/talon/tests/channels/test_base.py index 690ede839b9..372bb472e88 100644 --- a/libs/talon/tests/channels/test_base.py +++ b/libs/talon/tests/channels/test_base.py @@ -18,9 +18,10 @@ def test_default_exposure_allows_only_self_messages() -> None: - exposure = ChannelExposure(operator_id="operator") + exposure = ChannelExposure(operator_ids=frozenset({"operator"})) assert exposure.operator_ids == frozenset({"operator"}) + assert exposure.operator_id == "operator" assert exposure.allows(ChannelMessage(conversation_id="chat", text="hi", sender_id="operator")) assert exposure.allows( ChannelMessage( @@ -35,11 +36,11 @@ def test_default_exposure_allows_only_self_messages() -> None: def test_default_exposure_allows_multiple_operator_ids() -> None: exposure = ChannelExposure( - operator_id="operator", - operator_ids=frozenset({"backup-operator"}), + operator_ids=frozenset({"operator", "backup-operator"}), ) assert exposure.operator_ids == frozenset({"operator", "backup-operator"}) + assert exposure.operator_id in {"operator", "backup-operator"} assert exposure.allows(ChannelMessage(conversation_id="chat", text="hi", sender_id="operator")) assert exposure.allows( ChannelMessage(conversation_id="chat", text="hi", sender_id="backup-operator") diff --git a/libs/talon/tests/channels/test_telegram.py b/libs/talon/tests/channels/test_telegram.py index 13c4af5f7a9..2116473acea 100644 --- a/libs/talon/tests/channels/test_telegram.py +++ b/libs/talon/tests/channels/test_telegram.py @@ -153,7 +153,10 @@ def _make_config( session_dir=tmp_path / "telegram", inbound_media_dir=tmp_path / "telegram" / "media", outbound_media_dir=tmp_path, - exposure=exposure or ChannelExposure(operator_id=operator_id), + exposure=exposure + or ChannelExposure( + operator_ids=frozenset({operator_id}) if operator_id else frozenset(), + ), poll_interval_seconds=60, poll_timeout_seconds=1, operator_id=operator_id, @@ -222,7 +225,7 @@ def test_config_from_talon_env_maps_telegram_values(tmp_path: Path) -> None: assert telegram.inbound_media_dir == tmp_path / "assistant" / "media" / "inbound" / "telegram" assert telegram.exposure == ChannelExposure( mode=ExposureMode.ALLOWLIST, - operator_id="999", + operator_ids=frozenset({"999"}), conversations=frozenset({"123", "456"}), ) assert telegram.allowed_user_ids == frozenset({"777", "888"}) @@ -243,11 +246,11 @@ def test_config_from_talon_env_maps_multiple_operator_ids(tmp_path: Path) -> Non telegram = TelegramChannelConfig.from_talon_config(config) - assert telegram.operator_id == "999" + assert telegram.operator_id in {"999", "1000"} assert telegram.exposure == ChannelExposure( - operator_id="999", operator_ids=frozenset({"999", "1000"}), ) + assert telegram.exposure.operator_id in {"999", "1000"} assert telegram.exposure.allows( ChannelMessage(conversation_id="chat", text="hi", sender_id="999") ) @@ -862,7 +865,7 @@ async def call(self, method: str, **params: object) -> object: session_dir=tmp_path / "telegram", inbound_media_dir=tmp_path / "telegram" / "media", outbound_media_dir=tmp_path, - exposure=ChannelExposure(operator_id="111"), + exposure=ChannelExposure(operator_ids=frozenset({"111"})), poll_interval_seconds=60, poll_timeout_seconds=1, max_media_bytes=10, diff --git a/libs/talon/tests/channels/test_whatsapp.py b/libs/talon/tests/channels/test_whatsapp.py index 8e84d531b2c..40b6198edcf 100644 --- a/libs/talon/tests/channels/test_whatsapp.py +++ b/libs/talon/tests/channels/test_whatsapp.py @@ -97,10 +97,11 @@ def test_config_from_talon_env_maps_exposure( assert whatsapp.max_media_bytes == DEFAULT_WHATSAPP_MAX_MEDIA_BYTES assert whatsapp.exposure == ChannelExposure( mode=ExposureMode.ALLOWLIST, - operator_id="operator", + operator_ids=frozenset({"operator"}), conversations=frozenset({"chat-1", "chat-2"}), mention_patterns=("@agent *",), ) + assert whatsapp.exposure.operator_id == "operator" assert whatsapp.bot_header == "test bot" @@ -116,9 +117,9 @@ def test_config_from_talon_env_maps_multiple_operator_ids(tmp_path: Path) -> Non whatsapp = WhatsAppChannelConfig.from_talon_config(config) assert whatsapp.exposure == ChannelExposure( - operator_id="operator", operator_ids=frozenset({"operator", "backup-operator"}), ) + assert whatsapp.exposure.operator_id in {"operator", "backup-operator"} assert whatsapp.exposure.allows( ChannelMessage(conversation_id="chat", text="hi", sender_id="operator") ) @@ -245,7 +246,7 @@ async def test_channel_polls_and_dispatches_allowed_messages(tmp_path: Path) -> channel = WhatsAppChannel( WhatsAppChannelConfig( session_dir=tmp_path, - exposure=ChannelExposure(operator_id="operator"), + exposure=ChannelExposure(operator_ids=frozenset({"operator"})), poll_interval_seconds=60, health_interval_seconds=60, ), diff --git a/libs/talon/tests/conftest.py b/libs/talon/tests/conftest.py new file mode 100644 index 00000000000..8499a834e3b --- /dev/null +++ b/libs/talon/tests/conftest.py @@ -0,0 +1,54 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +from deepagents_talon.interfaces import ChannelMedia, ChannelMessage, ChannelStatus + +if TYPE_CHECKING: + from collections.abc import Awaitable, Callable + + +class RecordingChannel: + """Shared test double for channel adapters. + + Tracks sent messages and media, and supports injecting inbound messages + via ``receive``. + """ + + def __init__(self, provider: str = "test") -> None: + self.provider = provider + self.handler: Callable[[ChannelMessage], Awaitable[None]] | None = None + self.started = False + self.stopped = False + self.sent: list[tuple[str, str]] = [] + self.media: list[tuple[str, ChannelMedia]] = [] + self.status_report = ChannelStatus(provider=provider, connected=True, detail="connected") + + async def start(self) -> None: + self.started = True + + async def stop(self) -> None: + self.stopped = True + + def set_message_handler(self, handler: Callable[[ChannelMessage], Awaitable[None]]) -> None: + self.handler = handler + + async def send_message(self, conversation_id: str, text: str) -> None: + self.sent.append((conversation_id, text)) + + async def send_media(self, conversation_id: str, media: ChannelMedia) -> None: + self.media.append((conversation_id, media)) + self.sent.append((conversation_id, f"{media.media_type}:{media.path}")) + + async def edit_message(self, conversation_id: str, message_id: str, text: str) -> None: + self.sent.append((conversation_id, f"{message_id}:{text}")) + + async def status(self) -> ChannelStatus: + return self.status_report + + async def receive(self, text: str, *, conversation_id: str = "chat") -> None: + """Deliver an inbound message to the registered handler.""" + if self.handler is None: + msg = "channel handler was not registered" + raise AssertionError(msg) + await self.handler(ChannelMessage(conversation_id=conversation_id, text=text)) diff --git a/libs/talon/tests/integration_tests/test_telegram_host.py b/libs/talon/tests/integration_tests/test_telegram_host.py index 2b49e1c2348..39455df39dc 100644 --- a/libs/talon/tests/integration_tests/test_telegram_host.py +++ b/libs/talon/tests/integration_tests/test_telegram_host.py @@ -8,49 +8,13 @@ from deepagents_talon.channels.whatsapp import WhatsAppChannel from deepagents_talon.config import TalonConfig from deepagents_talon.host import TalonHost -from deepagents_talon.interfaces import AgentRequest, AgentResult, ChannelMessage, ChannelStatus +from deepagents_talon.interfaces import AgentRequest, AgentResult +from tests.conftest import RecordingChannel if TYPE_CHECKING: - from collections.abc import Awaitable, Callable from pathlib import Path -class RecordingChannel: - def __init__(self, provider: str) -> None: - self.provider = provider - self.handler: Callable[[ChannelMessage], Awaitable[None]] | None = None - self.started = False - self.stopped = False - self.status_report = ChannelStatus(provider=provider, connected=True, detail="connected") - - async def start(self) -> None: - self.started = True - - async def stop(self) -> None: - self.stopped = True - - def set_message_handler(self, handler: Callable[[ChannelMessage], Awaitable[None]]) -> None: - self.handler = handler - - async def send_message(self, conversation_id: str, text: str) -> None: - pass - - async def send_media(self, conversation_id: str, media: object) -> None: - pass - - async def edit_message(self, conversation_id: str, message_id: str, text: str) -> None: - pass - - async def status(self) -> ChannelStatus: - return self.status_report - - async def receive(self, text: str, *, conversation_id: str = "chat") -> None: - if self.handler is None: - msg = "channel handler was not registered" - raise AssertionError(msg) - await self.handler(ChannelMessage(conversation_id=conversation_id, text=text)) - - class EchoAgent: def __init__(self) -> None: self.requests: list[AgentRequest] = [] diff --git a/libs/talon/tests/test_host.py b/libs/talon/tests/test_host.py index 878713808da..1d147f10ff1 100644 --- a/libs/talon/tests/test_host.py +++ b/libs/talon/tests/test_host.py @@ -11,46 +11,14 @@ AgentResult, ChannelMedia, ChannelMessage, - ChannelStatus, ToolApprovalRequest, ) +from tests.conftest import RecordingChannel if TYPE_CHECKING: - from collections.abc import Awaitable, Callable from pathlib import Path -class RecordingChannel: - def __init__(self) -> None: - self.handler: Callable[[ChannelMessage], Awaitable[None]] | None = None - self.started = False - self.stopped = False - self.sent: list[tuple[str, str]] = [] - self.media: list[tuple[str, ChannelMedia]] = [] - - async def start(self) -> None: - self.started = True - - async def stop(self) -> None: - self.stopped = True - - def set_message_handler(self, handler: Callable[[ChannelMessage], Awaitable[None]]) -> None: - self.handler = handler - - async def send_message(self, conversation_id: str, text: str) -> None: - self.sent.append((conversation_id, text)) - - async def send_media(self, conversation_id: str, media: ChannelMedia) -> None: - self.media.append((conversation_id, media)) - self.sent.append((conversation_id, f"{media.media_type}:{media.path}")) - - async def edit_message(self, conversation_id: str, message_id: str, text: str) -> None: - self.sent.append((conversation_id, f"{message_id}:{text}")) - - async def status(self) -> ChannelStatus: - return ChannelStatus(provider="test", connected=True) - - class RecordingScheduler: def __init__(self) -> None: self.started = False From 776e6cbc9144ddf0d9fdd9e141e1f9dd0dee896e Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sun, 21 Jun 2026 12:01:22 -0700 Subject: [PATCH 17/48] fix(talon): resolve ty type errors and OpenSWE Telegram API error handling --- libs/talon/deepagents_talon/__main__.py | 4 ++-- .../deepagents_talon/channels/telegram.py | 23 ++++++++++++------- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/libs/talon/deepagents_talon/__main__.py b/libs/talon/deepagents_talon/__main__.py index 97b4a31a6a1..e8abd6db237 100644 --- a/libs/talon/deepagents_talon/__main__.py +++ b/libs/talon/deepagents_talon/__main__.py @@ -29,7 +29,7 @@ from deepagents_talon.speech import build_voice_transcriber if TYPE_CHECKING: - from collections.abc import Sequence + from collections.abc import Mapping, Sequence from deepagents_talon.cron import CronJob from deepagents_talon.interfaces import ChannelAdapter @@ -206,7 +206,7 @@ def _channels( return tuple(channels) -def _env_enabled(env: dict[str, str], key: str) -> bool: +def _env_enabled(env: Mapping[str, str], key: str) -> bool: """Check whether a boolean environment flag is truthy. Args: diff --git a/libs/talon/deepagents_talon/channels/telegram.py b/libs/talon/deepagents_talon/channels/telegram.py index ef598bf0a14..3d83f70cedf 100644 --- a/libs/talon/deepagents_talon/channels/telegram.py +++ b/libs/talon/deepagents_talon/channels/telegram.py @@ -286,6 +286,7 @@ def _send_request(self, method: str, request: urllib.request.Request) -> object: except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as error: msg = f"Telegram Bot API request failed: {method}" raise TelegramError(msg) from error + _validate_response(payload) return payload @@ -955,6 +956,19 @@ def _extract_media_info(msg: Mapping[str, object]) -> _TelegramMediaInfo | None: return None +def _safe_file_size(obj: Mapping[str, object]) -> int: + """Extract a numeric file_size from a Telegram photo size object. + + Args: + obj: Telegram photo size mapping. + + Returns: + Integer file size, or ``0`` if absent or non-integer. + """ + raw = obj.get("file_size") + return raw if isinstance(raw, int) else 0 + + def _largest_photo_file_id(photo_sizes: object) -> str | None: """Extract the file_id of the largest photo size from a photo array. @@ -969,14 +983,7 @@ def _largest_photo_file_id(photo_sizes: object) -> str | None: sizes = [size for size in photo_sizes if isinstance(size, dict)] if not sizes: return None - best = max( - sizes, - key=lambda s: ( - cast("Mapping[str, object]", s).get("file_size", 0) - if isinstance(cast("Mapping[str, object]", s).get("file_size"), int) - else 0 - ), - ) + best = max(sizes, key=lambda s: _safe_file_size(cast("Mapping[str, object]", s))) file_id = cast("Mapping[str, object]", best).get("file_id") return file_id if isinstance(file_id, str) else None From f539d357ea85da9345dfa0f99b0755c2030bd6de Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sun, 21 Jun 2026 12:06:38 -0700 Subject: [PATCH 18/48] fix(talon): namespace channel conversation state --- libs/talon/deepagents_talon/host.py | 65 +++++++++++++++---- .../integration_tests/test_telegram_host.py | 13 +++- 2 files changed, 61 insertions(+), 17 deletions(-) diff --git a/libs/talon/deepagents_talon/host.py b/libs/talon/deepagents_talon/host.py index 6a3f3197d9a..be69bf7dc94 100644 --- a/libs/talon/deepagents_talon/host.py +++ b/libs/talon/deepagents_talon/host.py @@ -13,10 +13,10 @@ from collections import defaultdict from collections.abc import Awaitable, Callable from dataclasses import dataclass -from pathlib import Path from types import FrameType from typing import TYPE_CHECKING, cast +from deepagents_talon.channels.base import outbound_media_root_from_env from deepagents_talon.interfaces import ( AgentRequest, AgentResult, @@ -40,6 +40,7 @@ if TYPE_CHECKING: from collections.abc import Sequence + from pathlib import Path from deepagents_talon.config import TalonConfig from deepagents_talon.cron.jobs import CronJob @@ -54,8 +55,6 @@ _NEW_CONVERSATION_MESSAGE = "Started a fresh conversation." _APPROVE_REPLIES = frozenset({"approve", "approved", "yes", "y"}) _DENY_REPLIES = frozenset({"deny", "denied", "reject", "rejected", "no", "n"}) -_OUTBOUND_MEDIA_DIR_ENV = "DEEPAGENTS_TALON_OUTBOUND_MEDIA_DIR" -_WORKSPACE_ENV = "DEEPAGENTS_TALON_WORKSPACE" _RESET_THREAD_SEPARATOR = ":talon-reset:" @@ -164,12 +163,22 @@ async def receive_message(self, channel: ChannelAdapter, message: ChannelMessage channel: Channel that delivered the message. message: Inbound message to process. """ + provider = await _channel_provider(channel) command = _command_name(message.text) channel_conversation_id = message.conversation_id - agent_conversation_id = self._agent_conversation_id(channel_conversation_id) + conversation_root = self._channel_conversation_root( + channel, + provider, + channel_conversation_id, + ) + agent_conversation_id = self._agent_conversation_id(conversation_root) if command == _NEW_COMMAND: - await self._start_new_conversation(channel, channel_conversation_id) + await self._start_new_conversation( + channel, + channel_conversation_id, + conversation_root=conversation_root, + ) return if command == _STOP_COMMAND: @@ -186,7 +195,7 @@ async def receive_message(self, channel: ChannelAdapter, message: ChannelMessage return task = asyncio.create_task( - self._run_agent_turn(channel, message, agent_conversation_id), + self._run_agent_turn(channel, message, agent_conversation_id, provider), name=f"talon:{agent_conversation_id}", ) self._track_conversation_task(agent_conversation_id, task) @@ -196,10 +205,10 @@ async def _run_agent_turn( channel: ChannelAdapter, message: ChannelMessage, agent_conversation_id: str, + provider: str | None, ) -> None: message = await transcribe_voice_message(self.voice_transcriber, message) message = _prepare_inbound_message(message) - provider = await _channel_provider(channel) metadata: dict[str, object] = { "channel": provider, "sender_id": message.sender_id, @@ -236,7 +245,11 @@ async def run_scheduled_job(self, job: CronJob) -> str: Returns: Agent text output for scheduler delivery handling. """ - conversation_id = self._agent_conversation_id(job.origin.conversation_id) + conversation_root = self._scheduled_conversation_root( + provider=job.origin.channel, + conversation_id=job.origin.conversation_id, + ) + conversation_id = self._agent_conversation_id(conversation_root) result = await self._invoke_agent( conversation_id=conversation_id, text=job.prompt, @@ -312,10 +325,12 @@ async def _start_new_conversation( self, channel: ChannelAdapter, conversation_id: str, + *, + conversation_root: str, ) -> None: - current_conversation_id = self._agent_conversation_id(conversation_id) + current_conversation_id = self._agent_conversation_id(conversation_root) await self._cancel_conversation_tasks(current_conversation_id) - self._conversation_resets[conversation_id] += 1 + self._conversation_resets[conversation_root] += 1 await channel.send_message(conversation_id, _NEW_CONVERSATION_MESSAGE) async def _cancel_conversation( @@ -356,6 +371,27 @@ def _agent_conversation_id(self, conversation_id: str) -> str: return conversation_id return f"{conversation_id}{_RESET_THREAD_SEPARATOR}{reset}" + def _channel_conversation_root( + self, + channel: ChannelAdapter, + provider: str | None, + conversation_id: str, + ) -> str: + if len(self.channels) <= 1: + return conversation_id + provider_key = provider or channel.__class__.__qualname__ + return _conversation_key(provider_key, conversation_id) + + def _scheduled_conversation_root( + self, + *, + provider: str | None, + conversation_id: str, + ) -> str: + if len(self.channels) <= 1 or provider is None: + return conversation_id + return _conversation_key(provider, conversation_id) + async def _cancel_all(self) -> None: tasks = { task @@ -551,10 +587,11 @@ def _outbound_media_from_refs( def _outbound_media_root(config: TalonConfig) -> Path: - raw = config.env.get(_OUTBOUND_MEDIA_DIR_ENV) or config.env.get(_WORKSPACE_ENV) - if raw: - return Path(raw).expanduser() - return Path.cwd() + return outbound_media_root_from_env(config.env) + + +def _conversation_key(provider: str, conversation_id: str) -> str: + return f"{provider}:{conversation_id}" def _with_failed_attachment_text(text: str, failed: list[str]) -> str: diff --git a/libs/talon/tests/integration_tests/test_telegram_host.py b/libs/talon/tests/integration_tests/test_telegram_host.py index 39455df39dc..b71f452e5b1 100644 --- a/libs/talon/tests/integration_tests/test_telegram_host.py +++ b/libs/talon/tests/integration_tests/test_telegram_host.py @@ -18,6 +18,7 @@ class EchoAgent: def __init__(self) -> None: self.requests: list[AgentRequest] = [] + self.history: dict[str, list[str]] = {} async def start(self) -> None: pass @@ -27,7 +28,10 @@ async def stop(self) -> None: async def invoke(self, request: AgentRequest) -> AgentResult: self.requests.append(request) - return AgentResult(text=f"reply:{request.text}") + history = self.history.setdefault(request.conversation_id, []) + seen = len(history) + history.append(request.text) + return AgentResult(text=f"seen:{seen}:{request.text}") def test_channels_factory_selects_configured_channels(tmp_path: Path) -> None: @@ -92,8 +96,8 @@ async def test_simultaneous_channels_coexist_without_interference(tmp_path: Path ) await host.start() - await whatsapp_channel.receive("hello from whatsapp", conversation_id="wa-chat") - await telegram_channel.receive("hello from telegram", conversation_id="tg-chat") + await whatsapp_channel.receive("hello from whatsapp", conversation_id="chat") + await telegram_channel.receive("hello from telegram", conversation_id="chat") await _drain() await host.stop() @@ -102,10 +106,13 @@ async def test_simultaneous_channels_coexist_without_interference(tmp_path: Path assert telegram_channel.started assert telegram_channel.stopped assert len(agent.requests) == 2 + assert agent.requests[0].conversation_id != agent.requests[1].conversation_id assert agent.requests[0].text == "hello from whatsapp" assert agent.requests[0].metadata["channel"] == "whatsapp" assert agent.requests[1].text == "hello from telegram" assert agent.requests[1].metadata["channel"] == "telegram" + assert whatsapp_channel.sent == [("chat", "seen:0:hello from whatsapp")] + assert telegram_channel.sent == [("chat", "seen:0:hello from telegram")] async def _drain() -> None: From f806c15898d6f13b012d56ea59ae26bdd2dec718 Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sun, 21 Jun 2026 12:06:48 -0700 Subject: [PATCH 19/48] fix(talon): share channel media roots --- libs/talon/deepagents_talon/channels/base.py | 22 +++++- .../deepagents_talon/channels/telegram.py | 9 +-- .../deepagents_talon/channels/whatsapp.py | 22 +++--- libs/talon/tests/channels/test_base.py | 22 ++++++ libs/talon/tests/channels/test_telegram.py | 72 ++++++++++++++++++- 5 files changed, 127 insertions(+), 20 deletions(-) diff --git a/libs/talon/deepagents_talon/channels/base.py b/libs/talon/deepagents_talon/channels/base.py index a4dbd94a0da..acf0f93aedf 100644 --- a/libs/talon/deepagents_talon/channels/base.py +++ b/libs/talon/deepagents_talon/channels/base.py @@ -26,6 +26,8 @@ DEFAULT_MAX_MEDIA_BYTES = 1024 * 1024 * 1024 MAX_MEDIA_BYTES_ENV = "DEEPAGENTS_TALON_MAX_MEDIA_BYTES" OPEN_EXPOSURE_ACK_VALUE = "allow-arbitrary-senders" +OUTBOUND_MEDIA_DIR_ENV = "DEEPAGENTS_TALON_OUTBOUND_MEDIA_DIR" +WORKSPACE_ENV = "DEEPAGENTS_TALON_WORKSPACE" _LINK_PATTERN = re.compile(r"\[([^\]]+)]\(([^)]+)\)") _HEADING_PATTERN = re.compile(r"^#{1,6}\s+", flags=re.MULTILINE) @@ -216,6 +218,21 @@ def channel_exposure_from_env( ) +def outbound_media_root_from_env(env: Mapping[str, str]) -> Path: + """Return the trusted outbound media root for channel attachments. + + Args: + env: Environment variable mapping. + + Returns: + Configured outbound media directory, workspace directory, or cwd. + """ + raw = env.get(OUTBOUND_MEDIA_DIR_ENV) or env.get(WORKSPACE_ENV) + if raw: + return Path(raw).expanduser() + return Path.cwd() + + def validate_media( media: ChannelMedia, *, @@ -284,6 +301,7 @@ def message_with_media_paths( *, media_paths: Sequence[str], mime_types: Sequence[str] = (), + has_media: bool | None = None, ) -> ChannelMessage: """Return `message` with normalized inbound-media path metadata. @@ -291,6 +309,8 @@ def message_with_media_paths( message: Original channel message. media_paths: Local media paths associated with the message. mime_types: MIME types aligned with `media_paths`. + has_media: Optional provider-reported media presence. When omitted, this + is inferred from `media_paths`. Returns: Channel message with standard media path metadata. @@ -303,7 +323,7 @@ def message_with_media_paths( metadata["media_mime_types"] = types metadata["media_types"] = types metadata["voice_path"] = paths[0] if paths and metadata.get("media_type") == "voice" else None - metadata["has_media"] = bool(paths) + metadata["has_media"] = bool(paths) if has_media is None else has_media return replace_message_metadata(message, metadata) diff --git a/libs/talon/deepagents_talon/channels/telegram.py b/libs/talon/deepagents_talon/channels/telegram.py index 3d83f70cedf..93198e14ec7 100644 --- a/libs/talon/deepagents_talon/channels/telegram.py +++ b/libs/talon/deepagents_talon/channels/telegram.py @@ -30,6 +30,7 @@ max_media_bytes_from_env, message_with_media_paths, optional_str, + outbound_media_root_from_env, parse_float, replace_message_metadata, split_csv, @@ -136,11 +137,7 @@ def from_talon_config(cls, config: TalonConfig) -> TelegramChannelConfig: str(config.inbound_media_dir / "telegram"), ), ) - outbound_media_dir = Path( - env.get("DEEPAGENTS_TALON_OUTBOUND_MEDIA_DIR") - or env.get("DEEPAGENTS_TALON_WORKSPACE") - or "/workspace", - ) + outbound_media_dir = outbound_media_root_from_env(env) exposure = channel_exposure_from_env( env, ChannelExposureEnv( @@ -1064,7 +1061,7 @@ def _save_offset(offset_file: Path, offset: int) -> None: """ offset_file.parent.mkdir(mode=0o700, parents=True, exist_ok=True) content = json.dumps({"offset": offset}) - tmp = offset_file.parent / f"{offset_file.name}.tmp" + tmp = offset_file.parent / f".{offset_file.name}.{secrets.token_hex(8)}.tmp" tmp.write_text(content, encoding="utf-8") tmp.chmod(0o600) tmp.replace(offset_file) diff --git a/libs/talon/deepagents_talon/channels/whatsapp.py b/libs/talon/deepagents_talon/channels/whatsapp.py index cb210e25b73..1aeaa464e4e 100644 --- a/libs/talon/deepagents_talon/channels/whatsapp.py +++ b/libs/talon/deepagents_talon/channels/whatsapp.py @@ -32,6 +32,7 @@ max_media_bytes_from_env, message_with_media_paths, optional_str, + outbound_media_root_from_env, parse_float, parse_int, replace_message_metadata, @@ -134,11 +135,7 @@ def from_talon_config(cls, config: TalonConfig) -> WhatsAppChannelConfig: str(config.inbound_media_dir / "whatsapp"), ), ) - outbound_media_dir = Path( - env.get("DEEPAGENTS_TALON_OUTBOUND_MEDIA_DIR") - or env.get("DEEPAGENTS_TALON_WORKSPACE") - or Path.cwd(), - ) + outbound_media_dir = outbound_media_root_from_env(env) command = _bridge_command(env) return cls( session_dir=session, @@ -605,7 +602,8 @@ def _parse_message(payload: object) -> ChannelMessage: text = values.get("text") if not isinstance(text, str): text = values.get("body") - return ChannelMessage( + has_media = bool(values.get("has_media") or values.get("hasMedia") or media_paths) + message = ChannelMessage( conversation_id=_required_str_any(values, ("chat_id", "chatId")), text=text if isinstance(text, str) else "", sender_id=optional_str(values.get("user_id") or values.get("senderId")), @@ -618,16 +616,16 @@ def _parse_message(payload: object) -> ChannelMessage: "chat_type": values.get("chat_type") or values.get("chatType"), "chat_id_from": values.get("chat_id_from") or values.get("chatIdFrom"), "user_name": values.get("user_name") or values.get("senderName"), - "media_paths": media_paths, - "media_path": media_paths[0] if media_paths else None, - "media_mime_types": media_mime_types, - "media_types": media_mime_types, - "voice_path": media_paths[0] if media_paths and media_type == "voice" else None, - "has_media": bool(values.get("has_media") or values.get("hasMedia") or media_paths), "raw_message": values.get("raw_message") or {}, "from_self": bool(values.get("from_self") or values.get("fromSelf")), }, ) + return message_with_media_paths( + message, + media_paths=media_paths, + mime_types=media_mime_types, + has_media=has_media, + ) def _enforce_inbound_media_cap(message: ChannelMessage, *, max_bytes: int) -> ChannelMessage: diff --git a/libs/talon/tests/channels/test_base.py b/libs/talon/tests/channels/test_base.py index 372bb472e88..c9c334fac5c 100644 --- a/libs/talon/tests/channels/test_base.py +++ b/libs/talon/tests/channels/test_base.py @@ -12,6 +12,7 @@ chunk_text, format_markdown_for_channel, max_media_bytes_from_env, + message_with_media_paths, validate_media, ) from deepagents_talon.interfaces import ChannelMedia, ChannelMessage @@ -126,6 +127,27 @@ def test_validate_media_rejects_type_mismatch(tmp_path: Path) -> None: validate_media(ChannelMedia(path=path, media_type="video")) +def test_message_with_media_paths_preserves_provider_media_presence() -> None: + message = ChannelMessage( + conversation_id="chat", + text="", + metadata={"media_type": "voice"}, + ) + + with_media = message_with_media_paths( + message, + media_paths=[], + mime_types=[], + has_media=True, + ) + + assert with_media.metadata["media_paths"] == [] + assert with_media.metadata["media_path"] is None + assert with_media.metadata["media_mime_types"] == [] + assert with_media.metadata["voice_path"] is None + assert with_media.metadata["has_media"] is True + + def test_max_media_bytes_from_env_defaults_to_one_gb() -> None: assert max_media_bytes_from_env({}) == DEFAULT_MAX_MEDIA_BYTES diff --git a/libs/talon/tests/channels/test_telegram.py b/libs/talon/tests/channels/test_telegram.py index 2116473acea..c1d60f96b90 100644 --- a/libs/talon/tests/channels/test_telegram.py +++ b/libs/talon/tests/channels/test_telegram.py @@ -31,6 +31,20 @@ from deepagents_talon.interfaces import ChannelMedia, ChannelMessage +class JsonResponse: + def __init__(self, payload: object) -> None: + self.payload = payload + + def __enter__(self) -> Self: + return self + + def __exit__(self, *args: object) -> None: + return None + + def read(self) -> bytes: + return json.dumps(self.payload).encode() + + class RecordingTransport: """Fake transport that records calls and returns canned responses.""" @@ -293,6 +307,25 @@ def test_config_accepts_telegram_bot_token_alias(tmp_path: Path) -> None: assert telegram.bot_token == "alias-token" # noqa: S105 # inert test token +def test_config_defaults_outbound_media_dir_to_cwd( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.chdir(tmp_path) + config = TalonConfig.from_env( + { + "AGENT_ASSISTANT_ID": "assistant", + "DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN": "token", + "DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID": "999", + }, + base_home=tmp_path / "home", + ) + + telegram = TelegramChannelConfig.from_talon_config(config) + + assert telegram.outbound_media_dir == tmp_path + + def test_config_requires_operator_for_self_exposure(tmp_path: Path) -> None: config = TalonConfig.from_env( { @@ -595,6 +628,43 @@ async def test_send_message_chunks_long_text(tmp_path: Path) -> None: assert len(cast("str", send_calls[1][1]["text"])) <= 4096 +async def test_transport_rejects_bot_api_error_envelopes( + monkeypatch: pytest.MonkeyPatch, +) -> None: + def fake_urlopen(request: object, *, timeout: float) -> JsonResponse: # noqa: ARG001 + return JsonResponse({"ok": False, "description": "bad request"}) + + monkeypatch.setattr("urllib.request.urlopen", fake_urlopen) + transport = TelegramTransport( + api_base="https://api.telegram.org", + token="test-token", # noqa: S106 # inert test token + timeout=1, + ) + + with pytest.raises(TelegramError, match="bad request"): + await transport.call("sendMessage", chat_id="123", text="hello") + + +async def test_transport_rejects_upload_error_envelopes( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + def fake_urlopen(request: object, *, timeout: float) -> JsonResponse: # noqa: ARG001 + return JsonResponse({"ok": False, "description": "upload rejected"}) + + image = tmp_path / "image.png" + image.write_bytes(b"image-data") + monkeypatch.setattr("urllib.request.urlopen", fake_urlopen) + transport = TelegramTransport( + api_base="https://api.telegram.org", + token="test-token", # noqa: S106 # inert test token + timeout=1, + ) + + with pytest.raises(TelegramError, match="upload rejected"): + await transport.upload("sendPhoto", file_field="photo", file_path=image, chat_id="123") + + # --- Outbound media tests --- @@ -932,7 +1002,7 @@ def test_offset_round_trip_uses_atomic_file_replace(tmp_path: Path) -> None: assert loaded == 100 assert offset_file.is_file() - assert not (tmp_path / "telegram_offset.json.tmp").exists() + assert sorted(path.name for path in tmp_path.iterdir()) == ["telegram_offset.json"] assert json.loads(offset_file.read_text(encoding="utf-8")) == {"offset": 100} From f507c9c5e76edace466dfe378bfd3f0f31ae7fee Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sun, 21 Jun 2026 12:51:16 -0700 Subject: [PATCH 20/48] refactor(talon): remove dead and redundant was a no-op in every code path: was always set to , which is derived from . When is empty, is , so the function returns early. When is non-empty, the second condition short-circuits. Remove the function, the field on , and the unused import from dataclasses. --- .../talon/deepagents_talon/channels/telegram.py | 17 ++--------------- libs/talon/tests/channels/test_telegram.py | 2 -- 2 files changed, 2 insertions(+), 17 deletions(-) diff --git a/libs/talon/deepagents_talon/channels/telegram.py b/libs/talon/deepagents_talon/channels/telegram.py index 93198e14ec7..0e70146a2cc 100644 --- a/libs/talon/deepagents_talon/channels/telegram.py +++ b/libs/talon/deepagents_talon/channels/telegram.py @@ -13,7 +13,7 @@ import secrets import urllib.error import urllib.request -from dataclasses import dataclass, field, replace +from dataclasses import dataclass, field from pathlib import Path from typing import TYPE_CHECKING, cast @@ -88,8 +88,6 @@ class TelegramChannelConfig: request_timeout_seconds: Per-request HTTP timeout for Bot API calls. max_media_bytes: Maximum media bytes allowed for inbound downloads and outbound local files before provider-specific limits are applied. - operator_id: First Telegram user ID for the operator, preserved for - compatibility with single-operator callers in self exposure mode. allowed_user_ids: Telegram user IDs allowed to trigger private chats in allowlist exposure mode. """ @@ -104,7 +102,6 @@ class TelegramChannelConfig: poll_interval_seconds: float = DEFAULT_POLL_INTERVAL_SECONDS request_timeout_seconds: float = DEFAULT_REQUEST_TIMEOUT_SECONDS max_media_bytes: int = DEFAULT_MAX_MEDIA_BYTES - operator_id: str | None = None allowed_user_ids: frozenset[str] = field(default_factory=frozenset) @classmethod @@ -170,7 +167,6 @@ def from_talon_config(cls, config: TalonConfig) -> TelegramChannelConfig: DEFAULT_REQUEST_TIMEOUT_SECONDS, ), max_media_bytes=max_media_bytes_from_env(env), - operator_id=exposure.operator_id, allowed_user_ids=frozenset( split_csv(env.get("DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_USERS", "")), ), @@ -312,7 +308,7 @@ def __init__( self._poll: asyncio.Task[None] | None = None self._stopped = asyncio.Event() self._status = ChannelStatus(provider="telegram", connected=False, detail="disconnected") - self._exposure = _effective_exposure(config.exposure, config.operator_id) + self._exposure = config.exposure self._bot_id: str | None = None self._bot_username: str | None = None self._offset = 0 @@ -691,15 +687,6 @@ def _form_field_value(value: object) -> str: return str(value) -def _effective_exposure( - exposure: ChannelExposure, - operator_id: str | None, -) -> ChannelExposure: - if exposure.mode != ExposureMode.SELF or exposure.operator_ids or operator_id is None: - return exposure - return replace(exposure, operator_ids=frozenset({operator_id})) - - def _with_from_self(message: ChannelMessage, bot_id: str | None) -> ChannelMessage: if bot_id is None or message.sender_id != bot_id: return message diff --git a/libs/talon/tests/channels/test_telegram.py b/libs/talon/tests/channels/test_telegram.py index c1d60f96b90..9766acb9e2e 100644 --- a/libs/talon/tests/channels/test_telegram.py +++ b/libs/talon/tests/channels/test_telegram.py @@ -173,7 +173,6 @@ def _make_config( ), poll_interval_seconds=60, poll_timeout_seconds=1, - operator_id=operator_id, allowed_user_ids=allowed_user_ids or frozenset(), ) @@ -260,7 +259,6 @@ def test_config_from_talon_env_maps_multiple_operator_ids(tmp_path: Path) -> Non telegram = TelegramChannelConfig.from_talon_config(config) - assert telegram.operator_id in {"999", "1000"} assert telegram.exposure == ChannelExposure( operator_ids=frozenset({"999", "1000"}), ) From ddaab98a294a7bf2b7c036eca8d18e40e341c000 Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sun, 21 Jun 2026 12:53:33 -0700 Subject: [PATCH 21/48] refactor(talon): move filter_capped_media_paths to whatsapp.py and inline dispatch_message MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit FilteredMediaPaths and filter_capped_media_paths were only used by the WhatsApp channel, not shared across channels. Move them from base.py into whatsapp.py as module-private helpers. Inline the three-line dispatch_message helper into both channels _dispatch methods — the indirection added no value. Fixes #2 and #11 (WhatsApp side). --- libs/talon/deepagents_talon/channels/base.py | 69 ---------------- .../deepagents_talon/channels/whatsapp.py | 82 +++++++++++++++++-- 2 files changed, 77 insertions(+), 74 deletions(-) diff --git a/libs/talon/deepagents_talon/channels/base.py b/libs/talon/deepagents_talon/channels/base.py index acf0f93aedf..0a5a7675bdf 100644 --- a/libs/talon/deepagents_talon/channels/base.py +++ b/libs/talon/deepagents_talon/channels/base.py @@ -74,23 +74,6 @@ class ChannelExposureEnv: require_self_operator: bool = False -@dataclass(frozen=True, slots=True) -class FilteredMediaPaths: - """Inbound media paths retained after applying local size caps. - - Args: - paths: String paths that remain usable. - mime_types: MIME types aligned with `paths`. - changed: Whether any input path was dropped or ignored. - errors: Human-readable drop reasons for logs or metadata. - """ - - paths: tuple[str, ...] - mime_types: tuple[str, ...] - changed: bool - errors: tuple[str, ...] = () - - @dataclass(frozen=True, slots=True) class ChannelExposure: """Inbound exposure policy shared by channel adapters. @@ -327,58 +310,6 @@ def message_with_media_paths( return replace_message_metadata(message, metadata) -def filter_capped_media_paths( - media_paths: Sequence[object], - mime_types: Sequence[object], - *, - max_bytes: int, -) -> FilteredMediaPaths: - """Filter inbound local media paths against a configured size cap. - - Args: - media_paths: Candidate local media paths from a channel payload. - mime_types: Candidate MIME types aligned with `media_paths`. - max_bytes: Maximum allowed file size. - - Returns: - Filter result containing kept paths and dropped-path reasons. - - Note: - Paths that do not exist on disk are silently kept. This is intentional: - WhatsApp bridge downloads may still be in progress when inbound messages - are polled, so a missing file does not indicate an oversized or invalid - download — only one that has not landed yet. - """ - kept: list[str] = [] - kept_mime_types: list[str] = [] - errors: list[str] = [] - changed = False - for index, raw_path in enumerate(media_paths): - if not isinstance(raw_path, str): - changed = True - continue - try: - validate_media_size(Path(raw_path), max_bytes=max_bytes) - except FileNotFoundError: - kept.append(raw_path) - except ChannelMediaError as error: - changed = True - errors.append(str(error)) - continue - else: - kept.append(raw_path) - if index < len(mime_types): - mime_type = mime_types[index] - if isinstance(mime_type, str): - kept_mime_types.append(mime_type) - return FilteredMediaPaths( - paths=tuple(kept), - mime_types=tuple(kept_mime_types), - changed=changed, - errors=tuple(errors), - ) - - def validate_media_size(path: Path, *, max_bytes: int) -> None: """Validate a local media file against the configured global cap. diff --git a/libs/talon/deepagents_talon/channels/whatsapp.py b/libs/talon/deepagents_talon/channels/whatsapp.py index 1aeaa464e4e..8e5613a96c0 100644 --- a/libs/talon/deepagents_talon/channels/whatsapp.py +++ b/libs/talon/deepagents_talon/channels/whatsapp.py @@ -24,10 +24,9 @@ MAX_TEXT_CHARS, ChannelExposure, ChannelExposureEnv, + ChannelMediaError, channel_exposure_from_env, chunk_text, - dispatch_message, - filter_capped_media_paths, format_markdown_for_channel, max_media_bytes_from_env, message_with_media_paths, @@ -37,11 +36,12 @@ parse_int, replace_message_metadata, validate_media, + validate_media_size, ) from deepagents_talon.interfaces import ChannelMedia, ChannelMessage, ChannelStatus, MessageHandler if TYPE_CHECKING: - from collections.abc import Mapping + from collections.abc import Mapping, Sequence from deepagents_talon.config import TalonConfig @@ -510,7 +510,10 @@ async def _stop_bridge_output_tasks(self) -> None: self._bridge_stderr = None async def _dispatch(self, message: ChannelMessage) -> None: - await dispatch_message(self._handler, message, provider="WhatsApp") + if self._handler is None: + logger.warning("Dropping WhatsApp message because no handler is registered") + return + await self._handler(message) async def _post_result(self, path: str, payload: Mapping[str, object]) -> object: response = await self._transport.post(path, payload) @@ -628,13 +631,82 @@ def _parse_message(payload: object) -> ChannelMessage: ) +@dataclass(frozen=True, slots=True) +class _FilteredMediaPaths: + """Inbound media paths retained after applying local size caps. + + Args: + paths: String paths that remain usable. + mime_types: MIME types aligned with `paths`. + changed: Whether any input path was dropped or ignored. + errors: Human-readable drop reasons for logs or metadata. + """ + + paths: tuple[str, ...] + mime_types: tuple[str, ...] + changed: bool + errors: tuple[str, ...] = () + + +def _filter_capped_media_paths( + media_paths: Sequence[object], + mime_types: Sequence[object], + *, + max_bytes: int, +) -> _FilteredMediaPaths: + """Filter inbound local media paths against a configured size cap. + + Args: + media_paths: Candidate local media paths from a channel payload. + mime_types: Candidate MIME types aligned with `media_paths`. + max_bytes: Maximum allowed file size. + + Returns: + Filter result containing kept paths and dropped-path reasons. + + Note: + Paths that do not exist on disk are silently kept. This is intentional: + WhatsApp bridge downloads may still be in progress when inbound messages + are polled, so a missing file does not indicate an oversized or invalid + download — only one that has not landed yet. + """ + kept: list[str] = [] + kept_mime_types: list[str] = [] + errors: list[str] = [] + changed = False + for index, raw_path in enumerate(media_paths): + if not isinstance(raw_path, str): + changed = True + continue + try: + validate_media_size(Path(raw_path), max_bytes=max_bytes) + except FileNotFoundError: + kept.append(raw_path) + except ChannelMediaError as error: + changed = True + errors.append(str(error)) + continue + else: + kept.append(raw_path) + if index < len(mime_types): + mime_type = mime_types[index] + if isinstance(mime_type, str): + kept_mime_types.append(mime_type) + return _FilteredMediaPaths( + paths=tuple(kept), + mime_types=tuple(kept_mime_types), + changed=changed, + errors=tuple(errors), + ) + + def _enforce_inbound_media_cap(message: ChannelMessage, *, max_bytes: int) -> ChannelMessage: media_paths = message.metadata.get("media_paths") if not isinstance(media_paths, list) or not media_paths: return message mime_types = message.metadata.get("media_mime_types") - filtered = filter_capped_media_paths( + filtered = _filter_capped_media_paths( media_paths=media_paths, mime_types=mime_types if isinstance(mime_types, list) else [], max_bytes=max_bytes, From 3fd15d250486e38a1c19bb89a588430e888f25a7 Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sun, 21 Jun 2026 12:54:41 -0700 Subject: [PATCH 22/48] refactor(talon): inline dispatch_message in telegram _dispatch and remove from base Both channels now inline the three-line null-check directly in their _dispatch methods. Remove the now-unused dispatch_message function from base.py and drop MessageHandler from its imports. Fixes #11 (Telegram side). --- libs/talon/deepagents_talon/channels/base.py | 21 +------------------ .../deepagents_talon/channels/telegram.py | 6 ++++-- 2 files changed, 5 insertions(+), 22 deletions(-) diff --git a/libs/talon/deepagents_talon/channels/base.py b/libs/talon/deepagents_talon/channels/base.py index 0a5a7675bdf..f83991b4260 100644 --- a/libs/talon/deepagents_talon/channels/base.py +++ b/libs/talon/deepagents_talon/channels/base.py @@ -14,7 +14,7 @@ from pathlib import Path from typing import TYPE_CHECKING -from deepagents_talon.interfaces import ChannelMedia, ChannelMessage, MessageHandler +from deepagents_talon.interfaces import ChannelMedia, ChannelMessage from deepagents_talon.media import resolve_bounded_media_path if TYPE_CHECKING: @@ -447,25 +447,6 @@ def _matches_text(text: str, patterns: tuple[str, ...]) -> bool: return any(fnmatch.fnmatchcase(text, pattern) for pattern in patterns) -async def dispatch_message( - handler: MessageHandler | None, - message: ChannelMessage, - *, - provider: str, -) -> None: - """Forward an inbound message to the registered handler. - - Args: - handler: Host callback for inbound messages, or ``None``. - message: Accepted inbound channel message. - provider: Provider name used in the drop warning when no handler is set. - """ - if handler is None: - logger.warning("Dropping %s message because no handler is registered", provider) - return - await handler(message) - - def _exposure_mode(value: str, *, provider: str) -> ExposureMode: try: return ExposureMode(value) diff --git a/libs/talon/deepagents_talon/channels/telegram.py b/libs/talon/deepagents_talon/channels/telegram.py index 0e70146a2cc..05a20eb54a4 100644 --- a/libs/talon/deepagents_talon/channels/telegram.py +++ b/libs/talon/deepagents_talon/channels/telegram.py @@ -26,7 +26,6 @@ ExposureMode, channel_exposure_from_env, chunk_text, - dispatch_message, max_media_bytes_from_env, message_with_media_paths, optional_str, @@ -519,7 +518,10 @@ def _commit_update_offset(self, update: Mapping[str, object]) -> None: _save_offset(self.config.offset_file, self._offset) async def _dispatch(self, message: ChannelMessage) -> None: - await dispatch_message(self._handler, message, provider="Telegram") + if self._handler is None: + logger.warning("Dropping Telegram message because no handler is registered") + return + await self._handler(message) async def _prepare_inbound_media(self, message: ChannelMessage) -> ChannelMessage: media_type = message.metadata.get("media_type") From d7bea1c19d9334fc9a2f24d352fc782957c4ffaa Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sun, 21 Jun 2026 12:57:02 -0700 Subject: [PATCH 23/48] refactor(talon): deduplicate send_media, eliminate double stat, inline _default_suffix, document group drops MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - send_media: replace if/else branch duplication with (method, file_field) tuple selection - _check_telegram_size: avoid redundant stat() call — the size is already checked by validate_media_size; reword the error without re-statting - _safe_suffix: inline the single-caller _default_suffix helper - TelegramChannel: document that group/supergroup messages are silently dropped and add a debug log in _message_values when chat type mismatches Fixes #3, #5, #14, #15. --- .../deepagents_talon/channels/telegram.py | 51 +++++++++---------- 1 file changed, 24 insertions(+), 27 deletions(-) diff --git a/libs/talon/deepagents_talon/channels/telegram.py b/libs/talon/deepagents_talon/channels/telegram.py index 05a20eb54a4..b60ba192b41 100644 --- a/libs/talon/deepagents_talon/channels/telegram.py +++ b/libs/talon/deepagents_talon/channels/telegram.py @@ -283,7 +283,11 @@ def _send_request(self, method: str, request: urllib.request.Request) -> object: class TelegramChannel: - """Channel adapter for Telegram via the Bot API with long polling.""" + """Channel adapter for Telegram via the Bot API with long polling. + + Only private chats and channel posts are processed. Messages from group + and supergroup chats are silently dropped during parsing. + """ def __init__( self, @@ -372,26 +376,20 @@ async def send_media(self, conversation_id: str, media: ChannelMedia) -> None: ) _check_telegram_size(checked) caption = await self._media_caption(conversation_id, checked.caption) - if checked.media_type == "image": - params: dict[str, object] = {"chat_id": conversation_id} - if caption: - params["caption"] = caption - await self._transport.upload( - "sendPhoto", - file_field="photo", - file_path=checked.path, - **params, - ) - else: - params = {"chat_id": conversation_id} - if caption: - params["caption"] = caption - await self._transport.upload( - "sendDocument", - file_field="document", - file_path=checked.path, - **params, - ) + method, file_field = ( + ("sendPhoto", "photo") + if checked.media_type == "image" + else ("sendDocument", "document") + ) + params: dict[str, object] = {"chat_id": conversation_id} + if caption: + params["caption"] = caption + await self._transport.upload( + method, + file_field=file_field, + file_path=checked.path, + **params, + ) async def send_typing(self, conversation_id: str) -> None: """Send a Telegram typing indicator. @@ -620,9 +618,8 @@ def _check_telegram_size(media: ChannelMedia) -> None: try: validate_media_size(media.path, max_bytes=limit) except ChannelMediaError: - size = media.path.stat().st_size label = "photo" if media.media_type == "image" else "document" - msg = f"{label} media is too large for Telegram: {size} bytes exceeds {limit}" + msg = f"{label} media is too large for Telegram: exceeds {limit} bytes" raise ChannelMediaError(msg) from None @@ -730,10 +727,6 @@ def _safe_suffix(file_path: str, media_type: str) -> str: return ".ogg" if re.fullmatch(r"\.[a-z0-9]{1,16}", suffix): return suffix - return _default_suffix(media_type) - - -def _default_suffix(media_type: str) -> str: if media_type == "image": return ".jpg" if media_type == "voice": @@ -856,6 +849,10 @@ def _message_values( chat_values = cast("Mapping[str, object]", chat) chat_type = chat_values.get("type") if chat_type != expected_chat_type: + logger.debug( + "Skipping Telegram update with chat type %r (expected %r)", + chat_type, expected_chat_type, + ) return None chat_id = chat_values.get("id") if not isinstance(chat_id, int): From 42c54da443a4aacf61b466023f1e68aa168c7cbc Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sun, 21 Jun 2026 12:58:38 -0700 Subject: [PATCH 24/48] refactor(talon): unify conversation-root methods and prevent _conversation_resets unbounded growth - Merge _channel_conversation_root and _scheduled_conversation_root into a single _conversation_root method with optional fallback_provider kwarg - Replace defaultdict(int) with a plain dict and .get() lookup so that _conversation_resets only holds entries for conversations that were actually reset, not every conversation ever seen Fixes #4 and #10. --- libs/talon/deepagents_talon/host.py | 35 ++++++++++++----------------- 1 file changed, 14 insertions(+), 21 deletions(-) diff --git a/libs/talon/deepagents_talon/host.py b/libs/talon/deepagents_talon/host.py index be69bf7dc94..c9255c8b23d 100644 --- a/libs/talon/deepagents_talon/host.py +++ b/libs/talon/deepagents_talon/host.py @@ -92,7 +92,7 @@ def __init__( self._locks: defaultdict[str, asyncio.Lock] = defaultdict(asyncio.Lock) self._tasks: dict[str, asyncio.Task[None]] = {} self._conversation_tasks: defaultdict[str, set[asyncio.Task[None]]] = defaultdict(set) - self._conversation_resets: defaultdict[str, int] = defaultdict(int) + self._conversation_resets: dict[str, int] = {} self._pending_tool_approvals: dict[str, _PendingToolApproval] = {} self._stopped = asyncio.Event() self._running = False @@ -166,10 +166,10 @@ async def receive_message(self, channel: ChannelAdapter, message: ChannelMessage provider = await _channel_provider(channel) command = _command_name(message.text) channel_conversation_id = message.conversation_id - conversation_root = self._channel_conversation_root( - channel, + conversation_root = self._conversation_root( provider, channel_conversation_id, + fallback_provider=channel.__class__.__qualname__, ) agent_conversation_id = self._agent_conversation_id(conversation_root) @@ -245,9 +245,9 @@ async def run_scheduled_job(self, job: CronJob) -> str: Returns: Agent text output for scheduler delivery handling. """ - conversation_root = self._scheduled_conversation_root( - provider=job.origin.channel, - conversation_id=job.origin.conversation_id, + conversation_root = self._conversation_root( + job.origin.channel, + job.origin.conversation_id, ) conversation_id = self._agent_conversation_id(conversation_root) result = await self._invoke_agent( @@ -330,7 +330,7 @@ async def _start_new_conversation( ) -> None: current_conversation_id = self._agent_conversation_id(conversation_root) await self._cancel_conversation_tasks(current_conversation_id) - self._conversation_resets[conversation_root] += 1 + self._conversation_resets[conversation_root] = self._conversation_resets.get(conversation_root, 0) + 1 await channel.send_message(conversation_id, _NEW_CONVERSATION_MESSAGE) async def _cancel_conversation( @@ -366,31 +366,24 @@ async def _cancel_conversation_tasks(self, conversation_id: str) -> bool: return True def _agent_conversation_id(self, conversation_id: str) -> str: - reset = self._conversation_resets[conversation_id] + reset = self._conversation_resets.get(conversation_id, 0) if reset == 0: return conversation_id return f"{conversation_id}{_RESET_THREAD_SEPARATOR}{reset}" - def _channel_conversation_root( + def _conversation_root( self, - channel: ChannelAdapter, provider: str | None, conversation_id: str, + *, + fallback_provider: str | None = None, ) -> str: if len(self.channels) <= 1: return conversation_id - provider_key = provider or channel.__class__.__qualname__ - return _conversation_key(provider_key, conversation_id) - - def _scheduled_conversation_root( - self, - *, - provider: str | None, - conversation_id: str, - ) -> str: - if len(self.channels) <= 1 or provider is None: + provider_key = provider or fallback_provider + if provider_key is None: return conversation_id - return _conversation_key(provider, conversation_id) + return _conversation_key(provider_key, conversation_id) async def _cancel_all(self) -> None: tasks = { From a07ce1503d1e55bf898368da8ed9642dfe9a330b Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sun, 21 Jun 2026 13:00:41 -0700 Subject: [PATCH 25/48] refactor(talon): deduplicate parse_float/parse_int, hoist error message, skip empty media metadata - Extract shared _parse_number helper for parse_float and parse_int - Hoist the duplicate error message in max_media_bytes_from_env above the try block so it is defined once - message_with_media_paths: only set media_paths/media_path/ media_mime_types/media_types/voice_path when media is actually present, reducing metadata noise on text-only messages Fixes #6, #7, #13. --- libs/talon/deepagents_talon/channels/base.py | 43 ++++++++++++-------- libs/talon/tests/channels/test_base.py | 8 ++-- libs/talon/tests/channels/test_whatsapp.py | 3 -- 3 files changed, 29 insertions(+), 25 deletions(-) diff --git a/libs/talon/deepagents_talon/channels/base.py b/libs/talon/deepagents_talon/channels/base.py index f83991b4260..d22818732bb 100644 --- a/libs/talon/deepagents_talon/channels/base.py +++ b/libs/talon/deepagents_talon/channels/base.py @@ -12,7 +12,7 @@ from dataclasses import dataclass, field from enum import StrEnum from pathlib import Path -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Callable, TypeVar from deepagents_talon.interfaces import ChannelMedia, ChannelMessage from deepagents_talon.media import resolve_bounded_media_path @@ -20,6 +20,8 @@ if TYPE_CHECKING: from collections.abc import Mapping, Sequence +_T = TypeVar("_T") + MAX_TEXT_CHARS = 4096 MAX_IMAGE_BYTES = 16 * 1024 * 1024 MAX_VIDEO_BYTES = 64 * 1024 * 1024 @@ -301,12 +303,14 @@ def message_with_media_paths( paths = list(media_paths) types = list(mime_types) metadata = dict(message.metadata) - metadata["media_paths"] = paths - metadata["media_path"] = paths[0] if paths else None - metadata["media_mime_types"] = types - metadata["media_types"] = types - metadata["voice_path"] = paths[0] if paths and metadata.get("media_type") == "voice" else None - metadata["has_media"] = bool(paths) if has_media is None else has_media + has_media_value = bool(paths) if has_media is None else has_media + metadata["has_media"] = has_media_value + if paths: + metadata["media_paths"] = paths + metadata["media_path"] = paths[0] + metadata["media_mime_types"] = types + metadata["media_types"] = types + metadata["voice_path"] = paths[0] if metadata.get("media_type") == "voice" else None return replace_message_metadata(message, metadata) @@ -341,13 +345,12 @@ def max_media_bytes_from_env(env: Mapping[str, str]) -> int: value = env.get(MAX_MEDIA_BYTES_ENV) if value is None: return DEFAULT_MAX_MEDIA_BYTES + msg = f"{MAX_MEDIA_BYTES_ENV} must be a positive integer byte count" try: parsed = int(value) except ValueError as error: - msg = f"{MAX_MEDIA_BYTES_ENV} must be a positive integer byte count" raise ValueError(msg) from error if parsed < 1: - msg = f"{MAX_MEDIA_BYTES_ENV} must be a positive integer byte count" raise ValueError(msg) return parsed @@ -365,13 +368,7 @@ def parse_float(value: str | None, default: float) -> float: Raises: ValueError: If `value` is not a float. """ - if value is None: - return default - try: - return float(value) - except ValueError as error: - msg = f"expected float value, got {value!r}" - raise ValueError(msg) from error + return _parse_number(float, value, default, label="float") def parse_int(value: str | None, default: int) -> int: @@ -387,12 +384,22 @@ def parse_int(value: str | None, default: int) -> int: Raises: ValueError: If `value` is not an integer. """ + return _parse_number(int, value, default, label="integer") + + +def _parse_number( + convert: Callable[[str], _T], + value: str | None, + default: _T, + *, + label: str, +) -> _T: if value is None: return default try: - return int(value) + return convert(value) # type: ignore[return-value] except ValueError as error: - msg = f"expected integer value, got {value!r}" + msg = f"expected {label} value, got {value!r}" raise ValueError(msg) from error diff --git a/libs/talon/tests/channels/test_base.py b/libs/talon/tests/channels/test_base.py index c9c334fac5c..90299acdbaf 100644 --- a/libs/talon/tests/channels/test_base.py +++ b/libs/talon/tests/channels/test_base.py @@ -141,10 +141,10 @@ def test_message_with_media_paths_preserves_provider_media_presence() -> None: has_media=True, ) - assert with_media.metadata["media_paths"] == [] - assert with_media.metadata["media_path"] is None - assert with_media.metadata["media_mime_types"] == [] - assert with_media.metadata["voice_path"] is None + assert "media_paths" not in with_media.metadata + assert "media_path" not in with_media.metadata + assert "media_mime_types" not in with_media.metadata + assert "voice_path" not in with_media.metadata assert with_media.metadata["has_media"] is True diff --git a/libs/talon/tests/channels/test_whatsapp.py b/libs/talon/tests/channels/test_whatsapp.py index 40b6198edcf..f88ecdf8e02 100644 --- a/libs/talon/tests/channels/test_whatsapp.py +++ b/libs/talon/tests/channels/test_whatsapp.py @@ -395,9 +395,6 @@ async def record(message: ChannelMessage) -> None: assert received[0].text == "oversized" assert received[0].metadata["has_media"] is False - assert received[0].metadata["media_paths"] == [] - assert received[0].metadata["media_path"] is None - assert received[0].metadata["voice_path"] is None assert "media_error" in received[0].metadata From 877603ed90376da3add1ae07f0de65856b50aadc Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sun, 21 Jun 2026 13:01:35 -0700 Subject: [PATCH 26/48] fix(talon): remove dead bridge.js fallback and catch per-update network errors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - bridge.js: remove dead DEEPAGENTS_TALON_MAX_MEDIA_BYTES fallback — the Python host only passes WHATSAPP_MAX_MEDIA_BYTES to the bridge subprocess - telegram.py: catch urllib.error.URLError and TimeoutError in _prepare_inbound_media so a failed media download for one update does not abort all remaining updates in the current getUpdates batch Fixes #8 and #9. --- libs/talon/deepagents_talon/channels/telegram.py | 2 +- libs/talon/deepagents_talon/channels/whatsapp_bridge/bridge.js | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/libs/talon/deepagents_talon/channels/telegram.py b/libs/talon/deepagents_talon/channels/telegram.py index b60ba192b41..f0f6763f4e3 100644 --- a/libs/talon/deepagents_talon/channels/telegram.py +++ b/libs/talon/deepagents_talon/channels/telegram.py @@ -535,7 +535,7 @@ async def _prepare_inbound_media(self, message: ChannelMessage) -> ChannelMessag media_type=media_type, message_id=message.message_id, ) - except ChannelMediaError as error: + except (ChannelMediaError, urllib.error.URLError, TimeoutError) as error: logger.warning( "Skipping Telegram inbound media for message %s: %s", message.message_id, diff --git a/libs/talon/deepagents_talon/channels/whatsapp_bridge/bridge.js b/libs/talon/deepagents_talon/channels/whatsapp_bridge/bridge.js index bcfae819754..d9b844708e1 100644 --- a/libs/talon/deepagents_talon/channels/whatsapp_bridge/bridge.js +++ b/libs/talon/deepagents_talon/channels/whatsapp_bridge/bridge.js @@ -14,8 +14,7 @@ const botHeader = process.env.WHATSAPP_BOT_HEADER || "deepagents bot"; const bridgeToken = process.env.WHATSAPP_BRIDGE_TOKEN || ""; const defaultWhatsAppMaxMediaBytes = 64 * 1024 * 1024; const rawMaxMediaBytes = Number( - process.env.DEEPAGENTS_TALON_MAX_MEDIA_BYTES || - process.env.WHATSAPP_MAX_MEDIA_BYTES || + process.env.WHATSAPP_MAX_MEDIA_BYTES || String(defaultWhatsAppMaxMediaBytes), ); const maxMediaBytes = From 5b77d3f53311712e56ab92736429c09b88e6236e Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sun, 21 Jun 2026 13:02:42 -0700 Subject: [PATCH 27/48] style(talon): fix ruff lint errors in base.py and host.py - Move Callable import to collections.abc under TYPE_CHECKING in base.py - Break long line in host.py _start_new_conversation --- libs/talon/deepagents_talon/channels/base.py | 4 ++-- libs/talon/deepagents_talon/host.py | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/libs/talon/deepagents_talon/channels/base.py b/libs/talon/deepagents_talon/channels/base.py index d22818732bb..234c3b5b94a 100644 --- a/libs/talon/deepagents_talon/channels/base.py +++ b/libs/talon/deepagents_talon/channels/base.py @@ -12,13 +12,13 @@ from dataclasses import dataclass, field from enum import StrEnum from pathlib import Path -from typing import TYPE_CHECKING, Callable, TypeVar +from typing import TYPE_CHECKING, TypeVar from deepagents_talon.interfaces import ChannelMedia, ChannelMessage from deepagents_talon.media import resolve_bounded_media_path if TYPE_CHECKING: - from collections.abc import Mapping, Sequence + from collections.abc import Callable, Mapping, Sequence _T = TypeVar("_T") diff --git a/libs/talon/deepagents_talon/host.py b/libs/talon/deepagents_talon/host.py index c9255c8b23d..1b7aa3208b2 100644 --- a/libs/talon/deepagents_talon/host.py +++ b/libs/talon/deepagents_talon/host.py @@ -330,7 +330,8 @@ async def _start_new_conversation( ) -> None: current_conversation_id = self._agent_conversation_id(conversation_root) await self._cancel_conversation_tasks(current_conversation_id) - self._conversation_resets[conversation_root] = self._conversation_resets.get(conversation_root, 0) + 1 + next_reset = self._conversation_resets.get(conversation_root, 0) + 1 + self._conversation_resets[conversation_root] = next_reset await channel.send_message(conversation_id, _NEW_CONVERSATION_MESSAGE) async def _cancel_conversation( From ea93a5f802690eefbe672223af69ab330054df6e Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sun, 21 Jun 2026 13:03:04 -0700 Subject: [PATCH 28/48] style(talon): format logger.debug call in _message_values --- libs/talon/deepagents_talon/channels/telegram.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/libs/talon/deepagents_talon/channels/telegram.py b/libs/talon/deepagents_talon/channels/telegram.py index f0f6763f4e3..c4b1c165956 100644 --- a/libs/talon/deepagents_talon/channels/telegram.py +++ b/libs/talon/deepagents_talon/channels/telegram.py @@ -851,7 +851,8 @@ def _message_values( if chat_type != expected_chat_type: logger.debug( "Skipping Telegram update with chat type %r (expected %r)", - chat_type, expected_chat_type, + chat_type, + expected_chat_type, ) return None chat_id = chat_values.get("id") From 511840e8e1861161f321126f3eaf0cc5632d845b Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sun, 21 Jun 2026 18:26:42 -0700 Subject: [PATCH 29/48] fix(talon): fix conversation key mismatch, double stat, add sendVideo and 429 handling - Use consistently for so conversation state is keyed the same regardless of whether succeeded - Eliminate double in Telegram outbound media: fold Telegram-specific size limits into via instead of a separate call - Add support so videos play inline instead of being sent as documents - Add to and respect 429 rate-limit responses in the polling loop instead of retrying immediately - Remove no-op call in that replaced metadata with an identical dict --- .../deepagents_talon/channels/telegram.py | 75 ++++++++++++------- libs/talon/deepagents_talon/host.py | 14 +--- libs/talon/tests/channels/test_telegram.py | 9 ++- 3 files changed, 55 insertions(+), 43 deletions(-) diff --git a/libs/talon/deepagents_talon/channels/telegram.py b/libs/talon/deepagents_talon/channels/telegram.py index c4b1c165956..057db9e092e 100644 --- a/libs/talon/deepagents_talon/channels/telegram.py +++ b/libs/talon/deepagents_talon/channels/telegram.py @@ -34,7 +34,6 @@ replace_message_metadata, split_csv, validate_media, - validate_media_size, ) from deepagents_talon.interfaces import ChannelMedia, ChannelMessage, ChannelStatus, MessageHandler @@ -51,6 +50,7 @@ DEFAULT_REQUEST_TIMEOUT_SECONDS = 35.0 MAX_PHOTO_BYTES = 10 * 1024 * 1024 MAX_DOCUMENT_BYTES = 50 * 1024 * 1024 +MAX_VIDEO_BYTES = 50 * 1024 * 1024 MAX_CAPTION_CHARS = 1024 OPEN_EXPOSURE_ACK_ENV = "DEEPAGENTS_TALON_TELEGRAM_OPEN_ACK" _OFFSET_FILENAME = "telegram_offset.json" @@ -58,7 +58,16 @@ class TelegramError(RuntimeError): - """Raised when the Telegram Bot API reports or causes a transport error.""" + """Raised when the Telegram Bot API reports or causes a transport error. + + Args: + message: Error description. + retry_after: Seconds to wait before retrying, as reported by a 429 response. + """ + + def __init__(self, message: str, *, retry_after: float | None = None) -> None: + super().__init__(message) + self.retry_after = retry_after @dataclass(frozen=True, slots=True) @@ -360,7 +369,7 @@ async def send_message(self, conversation_id: str, text: str) -> None: ) async def send_media(self, conversation_id: str, media: ChannelMedia) -> None: - """Send validated image or document media to a Telegram chat. + """Send validated image, video, or document media to a Telegram chat. Args: conversation_id: Telegram chat id. @@ -369,18 +378,14 @@ async def send_media(self, conversation_id: str, media: ChannelMedia) -> None: Raises: ChannelMediaError: If the media is too large or invalid. """ + telegram_limit = _telegram_media_limit(media.media_type) checked = validate_media( media, root=self.config.outbound_media_dir, - max_bytes=self.config.max_media_bytes, + max_bytes=min(self.config.max_media_bytes, telegram_limit), ) - _check_telegram_size(checked) caption = await self._media_caption(conversation_id, checked.caption) - method, file_field = ( - ("sendPhoto", "photo") - if checked.media_type == "image" - else ("sendDocument", "document") - ) + method, file_field = _telegram_send_method(checked.media_type) params: dict[str, object] = {"chat_id": conversation_id} if caption: params["caption"] = caption @@ -494,7 +499,21 @@ async def _poll_updates(self) -> None: message = await self._prepare_inbound_media(message) await self._dispatch(message) self._commit_update_offset(update) - except (TelegramError, urllib.error.URLError, TimeoutError): + except TelegramError as error: + delay = error.retry_after if error.retry_after is not None else self.config.poll_interval_seconds + logger.warning( + "Telegram long-polling error; retrying after %.1fs: %s", + delay, + error, + ) + self._status = ChannelStatus( + provider="telegram", + connected=False, + detail="polling error", + ) + await asyncio.sleep(delay) + continue + except (urllib.error.URLError, TimeoutError): logger.exception("Telegram long-polling error; retrying after interval") self._status = ChannelStatus( provider="telegram", @@ -545,10 +564,8 @@ async def _prepare_inbound_media(self, message: ChannelMessage) -> ChannelMessag metadata["has_media"] = False metadata["media_error"] = str(error) return replace_message_metadata(message, metadata) - metadata = dict(message.metadata) path = str(destination) - mime_type = _downloaded_mime_type(destination, metadata) - message = replace_message_metadata(message, metadata) + mime_type = _downloaded_mime_type(destination, dict(message.metadata)) return message_with_media_paths( message, media_paths=[path], @@ -605,22 +622,20 @@ async def _download_inbound_media( return destination -def _check_telegram_size(media: ChannelMedia) -> None: - """Validate media size against Telegram-specific limits. +def _telegram_media_limit(media_type: str) -> int: + """Return the Telegram Bot API upload size limit for a media type.""" + if media_type == "image": + return MAX_PHOTO_BYTES + return MAX_DOCUMENT_BYTES - Args: - media: Validated media payload. - Raises: - ChannelMediaError: If the file exceeds Telegram's size limit. - """ - limit = MAX_PHOTO_BYTES if media.media_type == "image" else MAX_DOCUMENT_BYTES - try: - validate_media_size(media.path, max_bytes=limit) - except ChannelMediaError: - label = "photo" if media.media_type == "image" else "document" - msg = f"{label} media is too large for Telegram: exceeds {limit} bytes" - raise ChannelMediaError(msg) from None +def _telegram_send_method(media_type: str) -> tuple[str, str]: + """Return the Bot API method and file field for a media type.""" + if media_type == "image": + return ("sendPhoto", "photo") + if media_type == "video": + return ("sendVideo", "video") + return ("sendDocument", "document") def _encode_multipart_form( @@ -768,7 +783,9 @@ def _validate_response(payload: object) -> object: if not values.get("ok", True): description = values.get("description", "unknown error") msg = f"Telegram Bot API error: {description}" - raise TelegramError(msg) + retry_after_raw = values.get("retry_after") + retry_after = float(retry_after_raw) if isinstance(retry_after_raw, (int, float)) else None + raise TelegramError(msg, retry_after=retry_after) return values.get("result") diff --git a/libs/talon/deepagents_talon/host.py b/libs/talon/deepagents_talon/host.py index 1b7aa3208b2..9f5a3d339dc 100644 --- a/libs/talon/deepagents_talon/host.py +++ b/libs/talon/deepagents_talon/host.py @@ -167,9 +167,8 @@ async def receive_message(self, channel: ChannelAdapter, message: ChannelMessage command = _command_name(message.text) channel_conversation_id = message.conversation_id conversation_root = self._conversation_root( - provider, + provider or type(channel).__name__, channel_conversation_id, - fallback_provider=channel.__class__.__qualname__, ) agent_conversation_id = self._agent_conversation_id(conversation_root) @@ -246,7 +245,7 @@ async def run_scheduled_job(self, job: CronJob) -> str: Agent text output for scheduler delivery handling. """ conversation_root = self._conversation_root( - job.origin.channel, + job.origin.channel or "cron", job.origin.conversation_id, ) conversation_id = self._agent_conversation_id(conversation_root) @@ -374,17 +373,12 @@ def _agent_conversation_id(self, conversation_id: str) -> str: def _conversation_root( self, - provider: str | None, + channel_key: str, conversation_id: str, - *, - fallback_provider: str | None = None, ) -> str: if len(self.channels) <= 1: return conversation_id - provider_key = provider or fallback_provider - if provider_key is None: - return conversation_id - return _conversation_key(provider_key, conversation_id) + return _conversation_key(channel_key, conversation_id) async def _cancel_all(self) -> None: tasks = { diff --git a/libs/talon/tests/channels/test_telegram.py b/libs/talon/tests/channels/test_telegram.py index 9766acb9e2e..e44372cb1ae 100644 --- a/libs/talon/tests/channels/test_telegram.py +++ b/libs/talon/tests/channels/test_telegram.py @@ -18,6 +18,7 @@ from deepagents_talon.channels.telegram import ( MAX_DOCUMENT_BYTES, MAX_PHOTO_BYTES, + MAX_VIDEO_BYTES, TelegramChannel, TelegramChannelConfig, TelegramError, @@ -68,7 +69,7 @@ async def call(self, method: str, **params: object) -> object: return {"ok": True, "result": updates} if method == "sendChatAction": return {"ok": True, "result": True} - if method in ("sendMessage", "sendPhoto", "sendDocument", "editMessageText"): + if method in ("sendMessage", "sendPhoto", "sendVideo", "sendDocument", "editMessageText"): return {"ok": True, "result": {"message_id": 42}} if method == "getFile": file_id = params.get("file_id") @@ -679,7 +680,7 @@ async def test_send_media_uses_expected_upload_method(tmp_path: Path) -> None: "photo", {"chat_id": "123", "caption": "cap"}, ), - ("clip.mp4", "video", None, "sendDocument", "document", {"chat_id": "123"}), + ("clip.mp4", "video", None, "sendVideo", "video", {"chat_id": "123"}), ) for filename, media_type, caption, method, file_field, params in cases: @@ -777,7 +778,7 @@ async def test_send_media_rejects_provider_oversized_files( ) -> None: cases: tuple[tuple[str, Literal["image", "video"], int], ...] = ( ("big.png", "image", MAX_PHOTO_BYTES + 1), - ("big.mp4", "video", MAX_DOCUMENT_BYTES + 1), + ("big.mp4", "video", MAX_VIDEO_BYTES + 1), ) for filename, media_type, fake_size in cases: @@ -787,7 +788,7 @@ async def test_send_media_rejects_provider_oversized_files( with monkeypatch.context() as patch: _patch_file_size(patch, path, fake_size) - with pytest.raises(ChannelMediaError, match="too large for Telegram"): + with pytest.raises(ChannelMediaError, match="too large"): await channel.send_media( "123", ChannelMedia(path=path, media_type=media_type), From e6169c468c0774a145bc8caa71514b9b8743799d Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sun, 21 Jun 2026 18:29:25 -0700 Subject: [PATCH 30/48] refactor(talon): deduplicate dispatch, validate_response, media keys, and bridge payloads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Extract shared `dispatch_message` helper in base.py, eliminating identical `_dispatch` methods in both channel adapters - Have `_send_request` return the validated `result` directly so `_extract_result` and `_extract_updates` skip re-validation - Drop redundant `media_types` metadata key — `media_mime_types` is the single canonical key everywhere - Send only camelCase keys to the WhatsApp bridge instead of doubling every payload with both snake_case and camelCase - Remove redundant `Math.min` clamp in bridge.js — the Python host already passes the clamped value via WHATSAPP_MAX_MEDIA_BYTES --- libs/talon/deepagents_talon/channels/base.py | 25 +++++++++++++-- .../deepagents_talon/channels/telegram.py | 32 +++++++------------ .../deepagents_talon/channels/whatsapp.py | 21 +++--------- .../channels/whatsapp_bridge/bridge.js | 10 +----- libs/talon/deepagents_talon/media.py | 1 - libs/talon/tests/channels/test_whatsapp.py | 7 +--- 6 files changed, 42 insertions(+), 54 deletions(-) diff --git a/libs/talon/deepagents_talon/channels/base.py b/libs/talon/deepagents_talon/channels/base.py index 234c3b5b94a..c5b76a91f60 100644 --- a/libs/talon/deepagents_talon/channels/base.py +++ b/libs/talon/deepagents_talon/channels/base.py @@ -14,7 +14,7 @@ from pathlib import Path from typing import TYPE_CHECKING, TypeVar -from deepagents_talon.interfaces import ChannelMedia, ChannelMessage +from deepagents_talon.interfaces import ChannelMedia, ChannelMessage, MessageHandler from deepagents_talon.media import resolve_bounded_media_path if TYPE_CHECKING: @@ -117,6 +117,28 @@ def allows(self, message: ChannelMessage) -> bool: ) +async def dispatch_message( + handler: MessageHandler | None, + message: ChannelMessage, + *, + provider: str, +) -> None: + """Dispatch an inbound message to the registered handler. + + Args: + handler: Host callback for inbound messages, or ``None``. + message: Channel message to dispatch. + provider: Provider name for log messages. + + Raises: + AssertionError: If no handler is registered (internal programming error). + """ + if handler is None: + logger.warning("Dropping %s message because no handler is registered", provider) + return + await handler(message) + + def format_markdown_for_channel(text: str) -> str: """Convert common Markdown into conservative WhatsApp-compatible text. @@ -309,7 +331,6 @@ def message_with_media_paths( metadata["media_paths"] = paths metadata["media_path"] = paths[0] metadata["media_mime_types"] = types - metadata["media_types"] = types metadata["voice_path"] = paths[0] if metadata.get("media_type") == "voice" else None return replace_message_metadata(message, metadata) diff --git a/libs/talon/deepagents_talon/channels/telegram.py b/libs/talon/deepagents_talon/channels/telegram.py index 057db9e092e..f6ec81ff385 100644 --- a/libs/talon/deepagents_talon/channels/telegram.py +++ b/libs/talon/deepagents_talon/channels/telegram.py @@ -26,6 +26,7 @@ ExposureMode, channel_exposure_from_env, chunk_text, + dispatch_message, max_media_bytes_from_env, message_with_media_paths, optional_str, @@ -287,8 +288,7 @@ def _send_request(self, method: str, request: urllib.request.Request) -> object: except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as error: msg = f"Telegram Bot API request failed: {method}" raise TelegramError(msg) from error - _validate_response(payload) - return payload + return _validate_response(payload) class TelegramChannel: @@ -497,7 +497,7 @@ async def _poll_updates(self) -> None: self._commit_update_offset(update) continue message = await self._prepare_inbound_media(message) - await self._dispatch(message) + await dispatch_message(self._handler, message, provider="Telegram") self._commit_update_offset(update) except TelegramError as error: delay = error.retry_after if error.retry_after is not None else self.config.poll_interval_seconds @@ -534,12 +534,6 @@ def _commit_update_offset(self, update: Mapping[str, object]) -> None: self._offset = next_offset _save_offset(self.config.offset_file, self._offset) - async def _dispatch(self, message: ChannelMessage) -> None: - if self._handler is None: - logger.warning("Dropping Telegram message because no handler is registered") - return - await self._handler(message) - async def _prepare_inbound_media(self, message: ChannelMessage) -> ChannelMessage: media_type = message.metadata.get("media_type") file_id = message.metadata.get("file_id") @@ -789,38 +783,36 @@ def _validate_response(payload: object) -> object: return values.get("result") -def _extract_result(payload: object) -> dict[str, object]: - """Extract the ``result`` field from a Bot API response. +def _extract_result(result: object) -> dict[str, object]: + """Extract a dict result from a validated Bot API response. Args: - payload: Full Bot API response. + result: Validated ``result`` field from a Bot API response. Returns: - The ``result`` object. + The result object as a dict. Raises: - TelegramError: If the response is malformed. + TelegramError: If the result is not a dict. """ - result = _validate_response(payload) if not isinstance(result, dict): msg = "Telegram Bot API response missing result" raise TelegramError(msg) return cast("dict[str, object]", result) -def _extract_updates(payload: object) -> list[dict[str, object]]: - """Extract the list of updates from a getUpdates response. +def _extract_updates(result: object) -> list[dict[str, object]]: + """Extract the list of updates from a getUpdates response result. Args: - payload: Full Bot API response. + result: Validated ``result`` field from a getUpdates response. Returns: List of update objects. Raises: - TelegramError: If the response is malformed. + TelegramError: If the result is not a list. """ - result = _validate_response(payload) if not isinstance(result, list): msg = "Telegram getUpdates result must be a list" raise TelegramError(msg) diff --git a/libs/talon/deepagents_talon/channels/whatsapp.py b/libs/talon/deepagents_talon/channels/whatsapp.py index 8e5613a96c0..f787b7cc100 100644 --- a/libs/talon/deepagents_talon/channels/whatsapp.py +++ b/libs/talon/deepagents_talon/channels/whatsapp.py @@ -27,6 +27,7 @@ ChannelMediaError, channel_exposure_from_env, chunk_text, + dispatch_message, format_markdown_for_channel, max_media_bytes_from_env, message_with_media_paths, @@ -313,7 +314,7 @@ async def send_message(self, conversation_id: str, text: str) -> None: text: Message content to send. """ for chunk in _chunk_with_bot_header(text, bot_header=self.config.bot_header): - await self._post_result("/send", {"chat_id": conversation_id, "text": chunk}) + await self._post_result("/send", {"chatId": conversation_id, "text": chunk}) async def send_media(self, conversation_id: str, media: ChannelMedia) -> None: """Send validated image or video media to a WhatsApp chat. @@ -329,9 +330,7 @@ async def send_media(self, conversation_id: str, media: ChannelMedia) -> None: ) staged = await asyncio.to_thread(_stage_bridge_media, checked.path, self.config) payload: dict[str, object] = { - "chat_id": conversation_id, "chatId": conversation_id, - "path": str(staged), "filePath": str(staged), "mediaType": checked.media_type, } @@ -349,7 +348,7 @@ async def send_typing(self, conversation_id: str) -> None: Args: conversation_id: WhatsApp chat id. """ - await self._post_result("/typing", {"chat_id": conversation_id, "chatId": conversation_id}) + await self._post_result("/typing", {"chatId": conversation_id}) async def edit_message(self, conversation_id: str, message_id: str, text: str) -> None: """Edit a previously sent WhatsApp message. @@ -362,12 +361,9 @@ async def edit_message(self, conversation_id: str, message_id: str, text: str) - await self._post_result( "/edit", { - "chat_id": conversation_id, "chatId": conversation_id, - "message_id": message_id, "messageId": message_id, "content": _with_bot_header(text, bot_header=self.config.bot_header), - "message": _with_bot_header(text, bot_header=self.config.bot_header), }, ) @@ -438,7 +434,7 @@ async def _poll_messages(self) -> None: message, max_bytes=self.config.max_media_bytes, ) - await self._dispatch(checked) + await dispatch_message(self._handler, checked, provider="WhatsApp") else: logger.debug( "Dropping WhatsApp message %s from %s due to exposure policy", @@ -509,12 +505,6 @@ async def _stop_bridge_output_tasks(self) -> None: self._bridge_stdout = None self._bridge_stderr = None - async def _dispatch(self, message: ChannelMessage) -> None: - if self._handler is None: - logger.warning("Dropping WhatsApp message because no handler is registered") - return - await self._handler(message) - async def _post_result(self, path: str, payload: Mapping[str, object]) -> object: response = await self._transport.post(path, payload) if isinstance(response, dict): @@ -595,8 +585,7 @@ def _parse_message(payload: object) -> ChannelMessage: media_mime_types = _str_list( values.get("media_mime_types") or values.get("mediaMimeTypes") - or values.get("mimeTypes") - or values.get("media_types"), + or values.get("mimeTypes"), ) message_type = optional_str( values.get("message_type") or values.get("messageType") or values.get("mediaType"), diff --git a/libs/talon/deepagents_talon/channels/whatsapp_bridge/bridge.js b/libs/talon/deepagents_talon/channels/whatsapp_bridge/bridge.js index d9b844708e1..ee0ea754f79 100644 --- a/libs/talon/deepagents_talon/channels/whatsapp_bridge/bridge.js +++ b/libs/talon/deepagents_talon/channels/whatsapp_bridge/bridge.js @@ -12,15 +12,7 @@ const sessionDir = path.resolve(process.env.WHATSAPP_SESSION_DIR || path.join(pr const mediaDir = path.resolve(process.env.WHATSAPP_MEDIA_DIR || path.join(sessionDir, "..", "media")); const botHeader = process.env.WHATSAPP_BOT_HEADER || "deepagents bot"; const bridgeToken = process.env.WHATSAPP_BRIDGE_TOKEN || ""; -const defaultWhatsAppMaxMediaBytes = 64 * 1024 * 1024; -const rawMaxMediaBytes = Number( - process.env.WHATSAPP_MAX_MEDIA_BYTES || - String(defaultWhatsAppMaxMediaBytes), -); -const maxMediaBytes = - Number.isFinite(rawMaxMediaBytes) && rawMaxMediaBytes > 0 - ? Math.min(rawMaxMediaBytes, defaultWhatsAppMaxMediaBytes) - : defaultWhatsAppMaxMediaBytes; +const maxMediaBytes = Number(process.env.WHATSAPP_MAX_MEDIA_BYTES) || (64 * 1024 * 1024); const webVersionCacheUrl = process.env.WHATSAPP_WEB_VERSION_CACHE_URL || "https://raw.githubusercontent.com/wppconnect-team/wa-version/main/html/2.3000.1026029003.html"; diff --git a/libs/talon/deepagents_talon/media.py b/libs/talon/deepagents_talon/media.py index d76b6217248..3018615cdde 100644 --- a/libs/talon/deepagents_talon/media.py +++ b/libs/talon/deepagents_talon/media.py @@ -300,7 +300,6 @@ def _media_mime_types(metadata: dict[str, object]) -> list[str]: raw = ( metadata.get("media_mime_types") or metadata.get("mime_types") - or metadata.get("media_types") ) if not isinstance(raw, list): return [] diff --git a/libs/talon/tests/channels/test_whatsapp.py b/libs/talon/tests/channels/test_whatsapp.py index f88ecdf8e02..1a06bf7b731 100644 --- a/libs/talon/tests/channels/test_whatsapp.py +++ b/libs/talon/tests/channels/test_whatsapp.py @@ -487,7 +487,7 @@ async def test_channel_sends_chunked_formatted_text(tmp_path: Path) -> None: assert transport.posts[0] == ( "/send", - {"chat_id": "chat", "text": "*deepagents bot*\n*bold*"}, + {"chatId": "chat", "text": "*deepagents bot*\n*bold*"}, ) assert transport.posts[1][0] == "/send" assert len(cast("str", transport.posts[1][1]["text"])) <= 4096 @@ -516,9 +516,7 @@ async def test_channel_sends_media_and_edits_messages(tmp_path: Path) -> None: ( "/send-media", { - "chat_id": "chat", "chatId": "chat", - "path": str(staged), "filePath": str(staged), "mediaType": "image", "caption": "*deepagents bot*\ncaption", @@ -527,12 +525,9 @@ async def test_channel_sends_media_and_edits_messages(tmp_path: Path) -> None: ( "/edit", { - "chat_id": "chat", "chatId": "chat", - "message_id": "message", "messageId": "message", "content": "*deepagents bot*\nUpdated", - "message": "*deepagents bot*\nUpdated", }, ), ] From eed91256010785096d7ab434ea3945ec0d7e9008 Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sun, 21 Jun 2026 18:33:26 -0700 Subject: [PATCH 31/48] refactor(talon): reduce over-engineering in channel adapters MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Inline dataclass and into — single-call-site helper that adds indirection without value - Simplify from 8 fields (5 env var name strings) to a prefix-based approach with 5 fields — callers pass a prefix like and the function derives var names - Remove backward-compat property on — all internal callers use - Inline in — trivial one-line wrapper - Inline in — one-line helper used in a single lambda - Replace with — is a frozen dataclass, is the standard way to create a copy with changed fields - Remove unused import from whatsapp.py TYPE_CHECKING block - Remove unused and imports from telegram.py - Remove unused import was re-added (still used by other functions) --- libs/talon/deepagents_talon/channels/base.py | 60 +++------- .../deepagents_talon/channels/telegram.py | 31 +---- .../deepagents_talon/channels/whatsapp.py | 108 +++++------------- libs/talon/deepagents_talon/host.py | 6 +- 4 files changed, 50 insertions(+), 155 deletions(-) diff --git a/libs/talon/deepagents_talon/channels/base.py b/libs/talon/deepagents_talon/channels/base.py index c5b76a91f60..0ddfd49463b 100644 --- a/libs/talon/deepagents_talon/channels/base.py +++ b/libs/talon/deepagents_talon/channels/base.py @@ -9,7 +9,7 @@ import logging import mimetypes import re -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from enum import StrEnum from pathlib import Path from typing import TYPE_CHECKING, TypeVar @@ -53,24 +53,18 @@ class ChannelMediaError(ValueError): @dataclass(frozen=True, slots=True) class ChannelExposureEnv: - """Environment variable names used to build channel exposure policy. + """Environment variable prefix and options for channel exposure policy. Args: provider: Human-readable provider name used in error messages. - exposure: Environment variable containing the exposure mode. - allowlist_chats: Environment variable containing allowlisted chats. - mention_patterns: Environment variable containing allowlist text patterns. - operator_id: Environment variable containing trusted operator ids. + env_prefix: Prefix for exposure env vars (e.g. ``DEEPAGENTS_TALON_TELEGRAM``). open_ack: Environment variable acknowledging open-exposure risk. open_ack_value: Required acknowledgement value for open exposure. require_self_operator: Whether `self` exposure requires an operator id. """ provider: str - exposure: str - allowlist_chats: str - mention_patterns: str - operator_id: str + env_prefix: str open_ack: str open_ack_value: str = OPEN_EXPOSURE_ACK_VALUE require_self_operator: bool = False @@ -93,11 +87,6 @@ class ChannelExposure: mention_patterns: tuple[str, ...] = () operator_ids: frozenset[str] = field(default_factory=frozenset) - @property - def operator_id(self) -> str | None: - """First operator id, or ``None`` when no operators are configured.""" - return next(iter(self.operator_ids), None) - def allows(self, message: ChannelMessage) -> bool: """Return whether an inbound message may trigger the agent. @@ -187,7 +176,7 @@ def channel_exposure_from_env( env: Mapping[str, str], config: ChannelExposureEnv, ) -> ChannelExposure: - """Build shared channel exposure policy from provider-specific env names. + """Build shared channel exposure policy from provider-specific env prefix. Args: env: Environment variable mapping. @@ -199,15 +188,18 @@ def channel_exposure_from_env( Raises: ValueError: If the exposure mode is invalid or risk acknowledgement is missing. """ + prefix = config.env_prefix + exposure_var = f"{prefix}_EXPOSURE" + operator_var = f"{prefix}_OPERATOR_ID" mode = _exposure_mode( - env.get(config.exposure, ExposureMode.SELF.value), + env.get(exposure_var, ExposureMode.SELF.value), provider=config.provider, ) - operator_ids = frozenset(split_csv(env.get(config.operator_id, ""))) + operator_ids = frozenset(split_csv(env.get(operator_var, ""))) if mode == ExposureMode.SELF and config.require_self_operator and not operator_ids: msg = ( - f"{config.provider} self exposure requires {config.operator_id}; " - f"set {config.exposure}=allowlist or open for other modes" + f"{config.provider} self exposure requires {operator_var}; " + f"set {exposure_var}=allowlist or open for other modes" ) raise ValueError(msg) if mode == ExposureMode.OPEN: @@ -219,8 +211,8 @@ def channel_exposure_from_env( ) return ChannelExposure( mode=mode, - conversations=frozenset(split_csv(env.get(config.allowlist_chats, ""))), - mention_patterns=tuple(split_csv(env.get(config.mention_patterns, ""))), + conversations=frozenset(split_csv(env.get(f"{prefix}_ALLOWLIST_CHATS", ""))), + mention_patterns=tuple(split_csv(env.get(f"{prefix}_MENTION_PATTERNS", ""))), operator_ids=operator_ids, ) @@ -281,28 +273,6 @@ def validate_media( return _validate_media_size(media, path=path, max_bytes=max_bytes) -def replace_message_metadata( - message: ChannelMessage, - metadata: Mapping[str, object], -) -> ChannelMessage: - """Return `message` with replaced metadata. - - Args: - message: Original channel message. - metadata: Replacement metadata. - - Returns: - Channel message with the same identity and text, plus new metadata. - """ - return ChannelMessage( - conversation_id=message.conversation_id, - text=message.text, - sender_id=message.sender_id, - message_id=message.message_id, - metadata=metadata, - ) - - def message_with_media_paths( message: ChannelMessage, *, @@ -332,7 +302,7 @@ def message_with_media_paths( metadata["media_path"] = paths[0] metadata["media_mime_types"] = types metadata["voice_path"] = paths[0] if metadata.get("media_type") == "voice" else None - return replace_message_metadata(message, metadata) + return replace(message, metadata=metadata) def validate_media_size(path: Path, *, max_bytes: int) -> None: diff --git a/libs/talon/deepagents_talon/channels/telegram.py b/libs/talon/deepagents_talon/channels/telegram.py index f6ec81ff385..0f2cf51541a 100644 --- a/libs/talon/deepagents_talon/channels/telegram.py +++ b/libs/talon/deepagents_talon/channels/telegram.py @@ -13,7 +13,7 @@ import secrets import urllib.error import urllib.request -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from pathlib import Path from typing import TYPE_CHECKING, cast @@ -31,9 +31,6 @@ message_with_media_paths, optional_str, outbound_media_root_from_env, - parse_float, - replace_message_metadata, - split_csv, validate_media, ) from deepagents_talon.interfaces import ChannelMedia, ChannelMessage, ChannelStatus, MessageHandler @@ -148,10 +145,7 @@ def from_talon_config(cls, config: TalonConfig) -> TelegramChannelConfig: env, ChannelExposureEnv( provider="Telegram", - exposure="DEEPAGENTS_TALON_TELEGRAM_EXPOSURE", - allowlist_chats="DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_CHATS", - mention_patterns="DEEPAGENTS_TALON_TELEGRAM_MENTION_PATTERNS", - operator_id="DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID", + env_prefix="DEEPAGENTS_TALON_TELEGRAM", open_ack=OPEN_EXPOSURE_ACK_ENV, require_self_operator=True, ), @@ -557,7 +551,7 @@ async def _prepare_inbound_media(self, message: ChannelMessage) -> ChannelMessag metadata = dict(message.metadata) metadata["has_media"] = False metadata["media_error"] = str(error) - return replace_message_metadata(message, metadata) + return replace(message, metadata=metadata) path = str(destination) mime_type = _downloaded_mime_type(destination, dict(message.metadata)) return message_with_media_paths( @@ -700,7 +694,7 @@ def _with_from_self(message: ChannelMessage, bot_id: str | None) -> ChannelMessa return message metadata = dict(message.metadata) metadata["from_self"] = True - return replace_message_metadata(message, metadata) + return replace(message, metadata=metadata) def _allows_telegram_message( @@ -949,19 +943,6 @@ def _extract_media_info(msg: Mapping[str, object]) -> _TelegramMediaInfo | None: return None -def _safe_file_size(obj: Mapping[str, object]) -> int: - """Extract a numeric file_size from a Telegram photo size object. - - Args: - obj: Telegram photo size mapping. - - Returns: - Integer file size, or ``0`` if absent or non-integer. - """ - raw = obj.get("file_size") - return raw if isinstance(raw, int) else 0 - - def _largest_photo_file_id(photo_sizes: object) -> str | None: """Extract the file_id of the largest photo size from a photo array. @@ -976,8 +957,8 @@ def _largest_photo_file_id(photo_sizes: object) -> str | None: sizes = [size for size in photo_sizes if isinstance(size, dict)] if not sizes: return None - best = max(sizes, key=lambda s: _safe_file_size(cast("Mapping[str, object]", s))) - file_id = cast("Mapping[str, object]", best).get("file_id") + best = max(sizes, key=lambda s: s.get("file_size") if isinstance(s.get("file_size"), int) else 0) + file_id = best.get("file_id") return file_id if isinstance(file_id, str) else None diff --git a/libs/talon/deepagents_talon/channels/whatsapp.py b/libs/talon/deepagents_talon/channels/whatsapp.py index f787b7cc100..095e20eb865 100644 --- a/libs/talon/deepagents_talon/channels/whatsapp.py +++ b/libs/talon/deepagents_talon/channels/whatsapp.py @@ -15,7 +15,7 @@ import urllib.error import urllib.parse import urllib.request -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from importlib.resources import files from pathlib import Path from typing import TYPE_CHECKING, cast @@ -35,14 +35,13 @@ outbound_media_root_from_env, parse_float, parse_int, - replace_message_metadata, validate_media, validate_media_size, ) from deepagents_talon.interfaces import ChannelMedia, ChannelMessage, ChannelStatus, MessageHandler if TYPE_CHECKING: - from collections.abc import Mapping, Sequence + from collections.abc import Mapping from deepagents_talon.config import TalonConfig @@ -148,10 +147,7 @@ def from_talon_config(cls, config: TalonConfig) -> WhatsAppChannelConfig: env, ChannelExposureEnv( provider="WhatsApp", - exposure="DEEPAGENTS_TALON_WHATSAPP_EXPOSURE", - allowlist_chats="DEEPAGENTS_TALON_WHATSAPP_ALLOWLIST_CHATS", - mention_patterns="DEEPAGENTS_TALON_WHATSAPP_MENTION_PATTERNS", - operator_id="DEEPAGENTS_TALON_WHATSAPP_OPERATOR_ID", + env_prefix="DEEPAGENTS_TALON_WHATSAPP", open_ack=OPEN_EXPOSURE_ACK_ENV, ), ), @@ -620,48 +616,21 @@ def _parse_message(payload: object) -> ChannelMessage: ) -@dataclass(frozen=True, slots=True) -class _FilteredMediaPaths: - """Inbound media paths retained after applying local size caps. +def _enforce_inbound_media_cap(message: ChannelMessage, *, max_bytes: int) -> ChannelMessage: + """Filter inbound media paths against a configured size cap. - Args: - paths: String paths that remain usable. - mime_types: MIME types aligned with `paths`. - changed: Whether any input path was dropped or ignored. - errors: Human-readable drop reasons for logs or metadata. + Paths that do not exist on disk are silently kept — WhatsApp bridge + downloads may still be in progress when inbound messages are polled. """ + media_paths = message.metadata.get("media_paths") + if not isinstance(media_paths, list) or not media_paths: + return message - paths: tuple[str, ...] - mime_types: tuple[str, ...] - changed: bool - errors: tuple[str, ...] = () - - -def _filter_capped_media_paths( - media_paths: Sequence[object], - mime_types: Sequence[object], - *, - max_bytes: int, -) -> _FilteredMediaPaths: - """Filter inbound local media paths against a configured size cap. + mime_types = message.metadata.get("media_mime_types") + mime_list = mime_types if isinstance(mime_types, list) else [] - Args: - media_paths: Candidate local media paths from a channel payload. - mime_types: Candidate MIME types aligned with `media_paths`. - max_bytes: Maximum allowed file size. - - Returns: - Filter result containing kept paths and dropped-path reasons. - - Note: - Paths that do not exist on disk are silently kept. This is intentional: - WhatsApp bridge downloads may still be in progress when inbound messages - are polled, so a missing file does not indicate an oversized or invalid - download — only one that has not landed yet. - """ kept: list[str] = [] kept_mime_types: list[str] = [] - errors: list[str] = [] changed = False for index, raw_path in enumerate(media_paths): if not isinstance(raw_path, str): @@ -670,53 +639,32 @@ def _filter_capped_media_paths( try: validate_media_size(Path(raw_path), max_bytes=max_bytes) except FileNotFoundError: - kept.append(raw_path) + pass # download may still be in progress except ChannelMediaError as error: + logger.warning( + "Skipping WhatsApp inbound media for message %s: %s", + message.message_id, + error, + ) changed = True - errors.append(str(error)) continue - else: - kept.append(raw_path) - if index < len(mime_types): - mime_type = mime_types[index] - if isinstance(mime_type, str): - kept_mime_types.append(mime_type) - return _FilteredMediaPaths( - paths=tuple(kept), - mime_types=tuple(kept_mime_types), - changed=changed, - errors=tuple(errors), - ) + kept.append(raw_path) + if index < len(mime_list): + mime = mime_list[index] + if isinstance(mime, str): + kept_mime_types.append(mime) - -def _enforce_inbound_media_cap(message: ChannelMessage, *, max_bytes: int) -> ChannelMessage: - media_paths = message.metadata.get("media_paths") - if not isinstance(media_paths, list) or not media_paths: - return message - - mime_types = message.metadata.get("media_mime_types") - filtered = _filter_capped_media_paths( - media_paths=media_paths, - mime_types=mime_types if isinstance(mime_types, list) else [], - max_bytes=max_bytes, - ) - for error in filtered.errors: - logger.warning( - "Skipping WhatsApp inbound media for message %s: %s", - message.message_id, - error, - ) - if not filtered.changed: + if not changed: return message checked = message_with_media_paths( message, - media_paths=filtered.paths, - mime_types=filtered.mime_types, + media_paths=tuple(kept), + mime_types=tuple(kept_mime_types), ) - if not filtered.paths: + if not kept: metadata = dict(checked.metadata) metadata["media_error"] = f"all media files exceeded {max_bytes} bytes" - return replace_message_metadata(checked, metadata) + return replace(checked, metadata=metadata) return checked diff --git a/libs/talon/deepagents_talon/host.py b/libs/talon/deepagents_talon/host.py index 9f5a3d339dc..195c2373c9b 100644 --- a/libs/talon/deepagents_talon/host.py +++ b/libs/talon/deepagents_talon/host.py @@ -461,7 +461,7 @@ async def _deliver_agent_result( media, failed = _outbound_media_from_refs( refs, cleaned, - root=_outbound_media_root(self.config), + root=outbound_media_root_from_env(self.config.env), ) text = _with_failed_attachment_text(cleaned, failed) sent_media, send_failed = await _send_channel_media( @@ -574,10 +574,6 @@ def _outbound_media_from_refs( return media, failed -def _outbound_media_root(config: TalonConfig) -> Path: - return outbound_media_root_from_env(config.env) - - def _conversation_key(provider: str, conversation_id: str) -> str: return f"{provider}:{conversation_id}" From bcbc5bebefb0fc958f05afbbc8261b74c8de395c Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sun, 21 Jun 2026 18:35:08 -0700 Subject: [PATCH 32/48] fix(talon): batch offset writes and harden Telegram parsing - Batch offset persistence: write offset to disk once after processing all updates in a getUpdates response instead of per-update - Replace _message_values 4-tuple with _MessageValues NamedTuple for self-documenting field access - Strengthen MIME type validation in _downloaded_mime_type: use regex match against standard MIME format instead of naive slash check - Strip all C0 control chars and DEL in _form_header_value, not just CR and LF, to prevent header injection - Narrow messageMediaSize in bridge.js from 8 candidate properties to the 2 that whatsapp-web.js actually exposes on _data --- .../deepagents_talon/channels/telegram.py | 76 ++++++++++++++----- .../channels/whatsapp_bridge/bridge.js | 11 +-- 2 files changed, 58 insertions(+), 29 deletions(-) diff --git a/libs/talon/deepagents_talon/channels/telegram.py b/libs/talon/deepagents_talon/channels/telegram.py index 0f2cf51541a..2a535bb22d2 100644 --- a/libs/talon/deepagents_talon/channels/telegram.py +++ b/libs/talon/deepagents_talon/channels/telegram.py @@ -15,7 +15,7 @@ import urllib.request from dataclasses import dataclass, field, replace from pathlib import Path -from typing import TYPE_CHECKING, cast +from typing import TYPE_CHECKING, NamedTuple, cast from deepagents_talon.channels.base import ( DEFAULT_MAX_MEDIA_BYTES, @@ -475,7 +475,6 @@ async def _poll_updates(self) -> None: for update in updates: message = _parse_update(update) if message is None: - self._commit_update_offset(update) continue message = _with_from_self(message, self._bot_id) if not _allows_telegram_message( @@ -488,11 +487,11 @@ async def _poll_updates(self) -> None: message.message_id, message.conversation_id, ) - self._commit_update_offset(update) continue message = await self._prepare_inbound_media(message) await dispatch_message(self._handler, message, provider="Telegram") - self._commit_update_offset(update) + if updates: + self._advance_offset(updates) except TelegramError as error: delay = error.retry_after if error.retry_after is not None else self.config.poll_interval_seconds logger.warning( @@ -518,11 +517,20 @@ async def _poll_updates(self) -> None: raise await asyncio.sleep(self.config.poll_interval_seconds) - def _commit_update_offset(self, update: Mapping[str, object]) -> None: - update_id = update.get("update_id") - if not isinstance(update_id, int): + def _advance_offset(self, updates: list[Mapping[str, object]]) -> None: + """Advance the persisted offset past the last update in the batch. + + Args: + updates: Updates from a single getUpdates response. + """ + max_id = -1 + for update in updates: + update_id = update.get("update_id") + if isinstance(update_id, int) and update_id >= max_id: + max_id = update_id + if max_id < 0: return - next_offset = update_id + 1 + next_offset = max_id + 1 if next_offset <= self._offset: return self._offset = next_offset @@ -677,8 +685,16 @@ def _encode_multipart_form( return b"".join(chunks) +_C0_CONTROL_RE = re.compile(r"[\x00-\x1f\x7f]") + + def _form_header_value(value: str) -> str: - return value.replace("\\", "\\\\").replace('"', '\\"').replace("\r", "").replace("\n", "") + """Escape a string for safe inclusion in a multipart form-data header. + + Strips all C0 control characters and DEL, then escapes backslashes and + double quotes to prevent header injection. + """ + return _C0_CONTROL_RE.sub("", value).replace("\\", "\\\\").replace('"', '\\"') def _form_field_value(value: object) -> str: @@ -711,14 +727,23 @@ def _allows_telegram_message( return exposure.allows(message) +_MIME_RE = re.compile(r"^[a-z]+/[a-z0-9.+\-]+$") + + def _downloaded_mime_type(path: Path, metadata: dict[str, object]) -> str | None: + """Determine MIME type for a downloaded media file. + + Checks metadata-provided MIME types first, falling back to file extension + guessing. Metadata values are validated against the standard MIME format + (``type/subtype``) rather than naively checking for a slash. + """ raw = metadata.get("mime_type") - if isinstance(raw, str) and "/" in raw: + if isinstance(raw, str) and _MIME_RE.match(raw): return raw raw_many = metadata.get("media_mime_types") if isinstance(raw_many, list): for item in raw_many: - if isinstance(item, str) and "/" in item: + if isinstance(item, str) and _MIME_RE.match(item): return item guessed, _ = mimetypes.guess_type(path) return guessed @@ -825,19 +850,27 @@ def _parse_update(update: Mapping[str, object]) -> ChannelMessage | None: values = _message_values(update) if values is None: return None - msg, chat_id, message_id, chat_type = values return ChannelMessage( - conversation_id=str(chat_id), - text=_message_text(msg), - sender_id=_sender_id(msg), - message_id=str(message_id), - metadata=_message_metadata(msg, chat_type=chat_type), + conversation_id=str(values.chat_id), + text=_message_text(values.msg), + sender_id=_sender_id(values.msg), + message_id=str(values.message_id), + metadata=_message_metadata(values.msg, chat_type=values.chat_type), ) +class _MessageValues(NamedTuple): + """Parsed core fields from a Telegram update payload.""" + + msg: Mapping[str, object] + chat_id: int + message_id: int + chat_type: str + + def _message_values( update: Mapping[str, object], -) -> tuple[Mapping[str, object], int, int, str] | None: +) -> _MessageValues | None: message = update.get("message") expected_chat_type = "private" if not isinstance(message, dict): @@ -864,7 +897,12 @@ def _message_values( message_id = msg.get("message_id") if not isinstance(message_id, int): return None - return msg, chat_id, message_id, expected_chat_type + return _MessageValues( + msg=msg, + chat_id=chat_id, + message_id=message_id, + chat_type=expected_chat_type, + ) def _sender_id(msg: Mapping[str, object]) -> str | None: diff --git a/libs/talon/deepagents_talon/channels/whatsapp_bridge/bridge.js b/libs/talon/deepagents_talon/channels/whatsapp_bridge/bridge.js index ee0ea754f79..41816141259 100644 --- a/libs/talon/deepagents_talon/channels/whatsapp_bridge/bridge.js +++ b/libs/talon/deepagents_talon/channels/whatsapp_bridge/bridge.js @@ -339,16 +339,7 @@ function messageMimeType(message, media) { function messageMediaSize(message) { const data = message && message._data ? message._data : {}; - const candidates = [ - message.size, - message.fileSize, - message.filesize, - message.mediaSize, - data.size, - data.fileSize, - data.filesize, - data.mediaSize, - ]; + const candidates = [data.size, data.fileSize]; for (const candidate of candidates) { const parsed = Number(candidate); if (Number.isFinite(parsed) && parsed >= 0) { From 26da2d5e6f312e7e5c76ccf059129fd289d2518d Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sun, 21 Jun 2026 18:40:24 -0700 Subject: [PATCH 33/48] fix(talon): update tests for refactored channel adapters - Update test transports to return result values directly (not full Bot API envelopes) matching the transport contract after commit 2 - Remove operator_id property assertions from all test files - Update offset test for batch-write behavior: offset now advances past failed media updates instead of stopping at them - Catch TelegramError in _prepare_inbound_media so getFile failures are handled as media errors, not polling errors - Extract _photo_size helper to fix type inference for max() key - Add docstring to TelegramError.__init__ - Remove unused MAX_DOCUMENT_BYTES import from test_telegram - Fix line length violations in telegram.py - Fix filePath key in WhatsApp media test (was using removed path key) --- .../deepagents_talon/channels/telegram.py | 23 +++++++--- libs/talon/tests/channels/test_base.py | 2 - libs/talon/tests/channels/test_telegram.py | 44 +++++++------------ libs/talon/tests/channels/test_whatsapp.py | 4 +- 4 files changed, 36 insertions(+), 37 deletions(-) diff --git a/libs/talon/deepagents_talon/channels/telegram.py b/libs/talon/deepagents_talon/channels/telegram.py index 2a535bb22d2..c2eefa9d131 100644 --- a/libs/talon/deepagents_talon/channels/telegram.py +++ b/libs/talon/deepagents_talon/channels/telegram.py @@ -31,6 +31,8 @@ message_with_media_paths, optional_str, outbound_media_root_from_env, + parse_float, + split_csv, validate_media, ) from deepagents_talon.interfaces import ChannelMedia, ChannelMessage, ChannelStatus, MessageHandler @@ -64,6 +66,7 @@ class TelegramError(RuntimeError): """ def __init__(self, message: str, *, retry_after: float | None = None) -> None: + """Initialize the Telegram error.""" super().__init__(message) self.retry_after = retry_after @@ -493,7 +496,11 @@ async def _poll_updates(self) -> None: if updates: self._advance_offset(updates) except TelegramError as error: - delay = error.retry_after if error.retry_after is not None else self.config.poll_interval_seconds + delay = ( + error.retry_after + if error.retry_after is not None + else self.config.poll_interval_seconds + ) logger.warning( "Telegram long-polling error; retrying after %.1fs: %s", delay, @@ -517,7 +524,7 @@ async def _poll_updates(self) -> None: raise await asyncio.sleep(self.config.poll_interval_seconds) - def _advance_offset(self, updates: list[Mapping[str, object]]) -> None: + def _advance_offset(self, updates: list[dict[str, object]]) -> None: """Advance the persisted offset past the last update in the batch. Args: @@ -550,7 +557,7 @@ async def _prepare_inbound_media(self, message: ChannelMessage) -> ChannelMessag media_type=media_type, message_id=message.message_id, ) - except (ChannelMediaError, urllib.error.URLError, TimeoutError) as error: + except (ChannelMediaError, TelegramError, urllib.error.URLError, TimeoutError) as error: logger.warning( "Skipping Telegram inbound media for message %s: %s", message.message_id, @@ -981,6 +988,12 @@ def _extract_media_info(msg: Mapping[str, object]) -> _TelegramMediaInfo | None: return None +def _photo_size(size: dict[str, object]) -> int: + """Extract a numeric file_size from a Telegram photo size object.""" + raw = size.get("file_size") + return raw if isinstance(raw, int) else 0 + + def _largest_photo_file_id(photo_sizes: object) -> str | None: """Extract the file_id of the largest photo size from a photo array. @@ -992,10 +1005,10 @@ def _largest_photo_file_id(photo_sizes: object) -> str | None: """ if not isinstance(photo_sizes, list): return None - sizes = [size for size in photo_sizes if isinstance(size, dict)] + sizes = [cast("dict[str, object]", s) for s in photo_sizes if isinstance(s, dict)] if not sizes: return None - best = max(sizes, key=lambda s: s.get("file_size") if isinstance(s.get("file_size"), int) else 0) + best = max(sizes, key=_photo_size) file_id = best.get("file_id") return file_id if isinstance(file_id, str) else None diff --git a/libs/talon/tests/channels/test_base.py b/libs/talon/tests/channels/test_base.py index 90299acdbaf..f99ea10b1cc 100644 --- a/libs/talon/tests/channels/test_base.py +++ b/libs/talon/tests/channels/test_base.py @@ -22,7 +22,6 @@ def test_default_exposure_allows_only_self_messages() -> None: exposure = ChannelExposure(operator_ids=frozenset({"operator"})) assert exposure.operator_ids == frozenset({"operator"}) - assert exposure.operator_id == "operator" assert exposure.allows(ChannelMessage(conversation_id="chat", text="hi", sender_id="operator")) assert exposure.allows( ChannelMessage( @@ -41,7 +40,6 @@ def test_default_exposure_allows_multiple_operator_ids() -> None: ) assert exposure.operator_ids == frozenset({"operator", "backup-operator"}) - assert exposure.operator_id in {"operator", "backup-operator"} assert exposure.allows(ChannelMessage(conversation_id="chat", text="hi", sender_id="operator")) assert exposure.allows( ChannelMessage(conversation_id="chat", text="hi", sender_id="backup-operator") diff --git a/libs/talon/tests/channels/test_telegram.py b/libs/talon/tests/channels/test_telegram.py index e44372cb1ae..62754844aae 100644 --- a/libs/talon/tests/channels/test_telegram.py +++ b/libs/talon/tests/channels/test_telegram.py @@ -16,7 +16,6 @@ ExposureMode, ) from deepagents_talon.channels.telegram import ( - MAX_DOCUMENT_BYTES, MAX_PHOTO_BYTES, MAX_VIDEO_BYTES, TelegramChannel, @@ -62,15 +61,15 @@ async def call(self, method: str, **params: object) -> object: self.calls.append((method, dict(params))) if method == "getMe": self._get_me_called = True - return {"ok": True, "result": {"id": 123456, "username": "test_bot"}} + return {"id": 123456, "username": "test_bot"} if method == "getUpdates": updates = self.updates self.updates = [] - return {"ok": True, "result": updates} + return updates if method == "sendChatAction": - return {"ok": True, "result": True} + return True if method in ("sendMessage", "sendPhoto", "sendVideo", "sendDocument", "editMessageText"): - return {"ok": True, "result": {"message_id": 42}} + return {"message_id": 42} if method == "getFile": file_id = params.get("file_id") if file_id == "voice123": @@ -79,8 +78,8 @@ async def call(self, method: str, **params: object) -> object: file_path = "documents/report.pdf" else: file_path = "photos/file.jpg" - return {"ok": True, "result": {"file_id": file_id, "file_path": file_path}} - return {"ok": True, "result": True} + return {"file_id": file_id, "file_path": file_path} + return True async def upload( self, @@ -91,7 +90,7 @@ async def upload( **params: object, ) -> object: self.uploads.append((method, file_field, file_path, dict(params))) - return {"ok": True, "result": {"message_id": 42}} + return {"message_id": 42} class ErrorOnFirstSuccessTransport: @@ -102,14 +101,14 @@ def __init__(self) -> None: async def call(self, method: str, **params: object) -> object: # noqa: ARG002 # test fake if method == "getMe": - return {"ok": True, "result": {"id": 123456, "username": "test_bot"}} + return {"id": 123456, "username": "test_bot"} if method == "getUpdates": self.calls += 1 if self.calls == 1: msg = "network error" raise TelegramError(msg) - return {"ok": True, "result": []} - return {"ok": True, "result": True} + return [] + return True def _make_update( # noqa: PLR0913 # test helper with many optional fields @@ -263,7 +262,6 @@ def test_config_from_talon_env_maps_multiple_operator_ids(tmp_path: Path) -> Non assert telegram.exposure == ChannelExposure( operator_ids=frozenset({"999", "1000"}), ) - assert telegram.exposure.operator_id in {"999", "1000"} assert telegram.exposure.allows( ChannelMessage(conversation_id="chat", text="hi", sender_id="999") ) @@ -908,12 +906,9 @@ async def call(self, method: str, **params: object) -> object: if method == "getFile": self.calls.append((method, dict(params))) return { - "ok": True, - "result": { - "file_id": params.get("file_id"), - "file_path": "documents/report.pdf", - "file_size": 11, - }, + "file_id": params.get("file_id"), + "file_path": "documents/report.pdf", + "file_size": 11, } return await super().call(method, **params) @@ -1055,7 +1050,7 @@ async def test_channel_loads_persisted_offset_on_start(tmp_path: Path) -> None: assert get_updates_calls[0][1]["offset"] == 100 -async def test_channel_does_not_persist_failed_media_update_offset(tmp_path: Path) -> None: +async def test_channel_advances_offset_past_failed_media_update(tmp_path: Path) -> None: class FailingGetFileTransport(RecordingTransport): async def call(self, method: str, **params: object) -> object: if method == "getFile": @@ -1086,16 +1081,11 @@ async def record(message: ChannelMessage) -> None: channel.set_message_handler(record) await channel.start() - deadline = asyncio.get_running_loop().time() + 2 - while asyncio.get_running_loop().time() < deadline: - status = await channel.status() - if status.detail == "polling error": - break - await asyncio.sleep(0.01) + await _wait_for_received(received, 2) await channel.stop() - assert [msg.text for msg in received] == ["before media"] - assert _load_offset(config.offset_file) == 11 + assert [msg.text for msg in received] == ["before media", "media"] + assert _load_offset(config.offset_file) == 12 async def _wait_for_received(messages: list[ChannelMessage], count: int) -> None: diff --git a/libs/talon/tests/channels/test_whatsapp.py b/libs/talon/tests/channels/test_whatsapp.py index 1a06bf7b731..028b5db4020 100644 --- a/libs/talon/tests/channels/test_whatsapp.py +++ b/libs/talon/tests/channels/test_whatsapp.py @@ -101,7 +101,6 @@ def test_config_from_talon_env_maps_exposure( conversations=frozenset({"chat-1", "chat-2"}), mention_patterns=("@agent *",), ) - assert whatsapp.exposure.operator_id == "operator" assert whatsapp.bot_header == "test bot" @@ -119,7 +118,6 @@ def test_config_from_talon_env_maps_multiple_operator_ids(tmp_path: Path) -> Non assert whatsapp.exposure == ChannelExposure( operator_ids=frozenset({"operator", "backup-operator"}), ) - assert whatsapp.exposure.operator_id in {"operator", "backup-operator"} assert whatsapp.exposure.allows( ChannelMessage(conversation_id="chat", text="hi", sender_id="operator") ) @@ -509,7 +507,7 @@ async def test_channel_sends_media_and_edits_messages(tmp_path: Path) -> None: ) await channel.edit_message("chat", "message", "# Updated") - staged = Path(cast("str", transport.posts[0][1]["path"])) + staged = Path(cast("str", transport.posts[0][1]["filePath"])) assert staged.parent == media_dir assert await asyncio.to_thread(staged.read_bytes) == b"image" assert transport.posts == [ From c1ecb1ee60cd37fc1114713c464bb5ef9d6b1e1e Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sun, 21 Jun 2026 19:35:06 -0700 Subject: [PATCH 34/48] refactor(talon): add SendResult, promote send_typing, expand media_type, centralize send retry - Add SendResult dataclass to interfaces.py with success, message_id, error, and retryable fields; change send_message, send_media, and edit_message on ChannelAdapter to return SendResult instead of None - Promote send_typing into the ChannelAdapter protocol, replacing the getattr duck-typing hack in host.py _send_typing with a direct call - Expand ChannelMedia.media_type literal from image|video to image|video|document|audio|voice so the type matches runtime behavior - Add send_with_retry helper to channels/base.py with exponential backoff for transient failures; route all outbound host sends through it - Update WhatsAppChannel and TelegramChannel to return SendResult from all send methods, extracting message_id from provider responses - Update test stubs (RecordingChannel, InMemoryChannel) to match new return types and implement send_typing --- libs/talon/deepagents_talon/__init__.py | 2 + .../deepagents_talon/channels/__init__.py | 4 + libs/talon/deepagents_talon/channels/base.py | 68 +++++++++++++++- .../deepagents_talon/channels/telegram.py | 39 +++++++-- .../deepagents_talon/channels/whatsapp.py | 38 +++++++-- libs/talon/deepagents_talon/host.py | 79 ++++++++++++------- libs/talon/deepagents_talon/interfaces.py | 41 +++++++++- libs/talon/deepagents_talon/media.py | 2 +- libs/talon/tests/conftest.py | 14 +++- .../integration_tests/test_core_flows.py | 24 ++++-- 10 files changed, 253 insertions(+), 58 deletions(-) diff --git a/libs/talon/deepagents_talon/__init__.py b/libs/talon/deepagents_talon/__init__.py index b9428b31b4e..0564e053602 100644 --- a/libs/talon/deepagents_talon/__init__.py +++ b/libs/talon/deepagents_talon/__init__.py @@ -24,6 +24,7 @@ ChannelMessage, ChannelStatus, CronScheduler, + SendResult, ToolApprovalDecision, ToolApprovalHandler, ToolApprovalRequest, @@ -58,6 +59,7 @@ "OpenAIVoiceTranscriber", "PersistentCronScheduler", "RuntimeAgentComponents", + "SendResult", "TalonConfig", "TalonHost", "ToolApprovalDecision", diff --git a/libs/talon/deepagents_talon/channels/__init__.py b/libs/talon/deepagents_talon/channels/__init__.py index 0a67d1f629f..ee888fa5c47 100644 --- a/libs/talon/deepagents_talon/channels/__init__.py +++ b/libs/talon/deepagents_talon/channels/__init__.py @@ -9,6 +9,8 @@ ExposureMode, chunk_text, format_markdown_for_channel, + is_retryable_error, + send_with_retry, validate_media, ) from deepagents_talon.channels.telegram import TelegramChannel, TelegramChannelConfig @@ -24,5 +26,7 @@ "WhatsAppChannelConfig", "chunk_text", "format_markdown_for_channel", + "is_retryable_error", + "send_with_retry", "validate_media", ] diff --git a/libs/talon/deepagents_talon/channels/base.py b/libs/talon/deepagents_talon/channels/base.py index 0ddfd49463b..0491abf0f82 100644 --- a/libs/talon/deepagents_talon/channels/base.py +++ b/libs/talon/deepagents_talon/channels/base.py @@ -5,6 +5,7 @@ from __future__ import annotations +import asyncio import fnmatch import logging import mimetypes @@ -14,11 +15,11 @@ from pathlib import Path from typing import TYPE_CHECKING, TypeVar -from deepagents_talon.interfaces import ChannelMedia, ChannelMessage, MessageHandler +from deepagents_talon.interfaces import ChannelMedia, ChannelMessage, MessageHandler, SendResult from deepagents_talon.media import resolve_bounded_media_path if TYPE_CHECKING: - from collections.abc import Callable, Mapping, Sequence + from collections.abc import Awaitable, Callable, Mapping, Sequence _T = TypeVar("_T") @@ -488,3 +489,66 @@ def _media_type(path: Path) -> str: return "video" msg = f"unsupported media mime type: {mime}" raise ChannelMediaError(msg) + + +_RETRYABLE_ERROR_FRAGMENTS = frozenset( + { + "connectionerror", + "connectionreset", + "connectionrefused", + "connecttimeout", + "timeout", + "broken pipe", + "remotedisconnected", + "eoferror", + "network", + "transient", + } +) + + +def is_retryable_error(error: str | None) -> bool: + """Return whether an error message looks like a transient network failure. + + Args: + error: Error string from a failed send operation. + + Returns: + `True` when the error text matches a known transient-network pattern. + """ + if error is None: + return False + lowered = error.lower() + return any(fragment in lowered for fragment in _RETRYABLE_ERROR_FRAGMENTS) + + +async def send_with_retry( + send_fn: Callable[[], Awaitable[SendResult]], + *, + max_retries: int = 2, + base_delay: float = 2.0, +) -> SendResult: + """Call a channel send function with automatic retry on transient errors. + + Args: + send_fn: Zero-argument coroutine that performs the actual send. + max_retries: Maximum number of retry attempts after the first failure. + base_delay: Base delay in seconds for exponential backoff. + + Returns: + The final `SendResult` from the send function. + """ + result = await send_fn() + if result.success: + return result + if not (result.retryable or is_retryable_error(result.error)): + return result + for attempt in range(1, max_retries + 1): + delay = base_delay * (2 ** (attempt - 1)) + await asyncio.sleep(delay) + result = await send_fn() + if result.success: + return result + if not (result.retryable or is_retryable_error(result.error)): + return result + return result diff --git a/libs/talon/deepagents_talon/channels/telegram.py b/libs/talon/deepagents_talon/channels/telegram.py index c2eefa9d131..ad5961a8960 100644 --- a/libs/talon/deepagents_talon/channels/telegram.py +++ b/libs/talon/deepagents_talon/channels/telegram.py @@ -35,7 +35,13 @@ split_csv, validate_media, ) -from deepagents_talon.interfaces import ChannelMedia, ChannelMessage, ChannelStatus, MessageHandler +from deepagents_talon.interfaces import ( + ChannelMedia, + ChannelMessage, + ChannelStatus, + MessageHandler, + SendResult, +) if TYPE_CHECKING: from collections.abc import Mapping @@ -351,27 +357,34 @@ async def stop(self) -> None: self._poll = None self._status = ChannelStatus(provider="telegram", connected=False, detail="disconnected") - async def send_message(self, conversation_id: str, text: str) -> None: + async def send_message(self, conversation_id: str, text: str) -> SendResult: """Send chunked plain text. Args: conversation_id: Telegram chat id. text: Message content to send. + + Returns: + Result indicating whether the send succeeded. """ for chunk in chunk_text(text, limit=MAX_TEXT_CHARS): - await self._transport.call( + payload = await self._transport.call( "sendMessage", chat_id=conversation_id, text=chunk, ) + return SendResult(success=True, message_id=_extract_telegram_message_id(payload)) - async def send_media(self, conversation_id: str, media: ChannelMedia) -> None: + async def send_media(self, conversation_id: str, media: ChannelMedia) -> SendResult: """Send validated image, video, or document media to a Telegram chat. Args: conversation_id: Telegram chat id. media: Media payload to send. + Returns: + Result indicating whether the send succeeded. + Raises: ChannelMediaError: If the media is too large or invalid. """ @@ -386,12 +399,13 @@ async def send_media(self, conversation_id: str, media: ChannelMedia) -> None: params: dict[str, object] = {"chat_id": conversation_id} if caption: params["caption"] = caption - await self._transport.upload( + payload = await self._transport.upload( method, file_field=file_field, file_path=checked.path, **params, ) + return SendResult(success=True, message_id=_extract_telegram_message_id(payload)) async def send_typing(self, conversation_id: str) -> None: """Send a Telegram typing indicator. @@ -408,13 +422,16 @@ async def send_typing(self, conversation_id: str) -> None: except TelegramError: logger.debug("Could not send Telegram typing indicator", exc_info=True) - async def edit_message(self, conversation_id: str, message_id: str, text: str) -> None: + async def edit_message(self, conversation_id: str, message_id: str, text: str) -> SendResult: """Edit a previously sent Telegram message. Args: conversation_id: Telegram chat id. message_id: Telegram message id. text: Replacement message content. + + Returns: + Result indicating whether the edit succeeded. """ await self._transport.call( "editMessageText", @@ -422,6 +439,7 @@ async def edit_message(self, conversation_id: str, message_id: str, text: str) - message_id=int(message_id), text=text, ) + return SendResult(success=True, message_id=message_id) async def status(self) -> ChannelStatus: """Report the most recent Telegram Bot API connection status.""" @@ -827,6 +845,15 @@ def _extract_result(result: object) -> dict[str, object]: return cast("dict[str, object]", result) +def _extract_telegram_message_id(payload: object) -> str | None: + """Extract a message id from a Bot API send response payload.""" + result = _extract_result(payload) + message_id = result.get("message_id") + if isinstance(message_id, int): + return str(message_id) + return None + + def _extract_updates(result: object) -> list[dict[str, object]]: """Extract the list of updates from a getUpdates response result. diff --git a/libs/talon/deepagents_talon/channels/whatsapp.py b/libs/talon/deepagents_talon/channels/whatsapp.py index 095e20eb865..18a16b80ab2 100644 --- a/libs/talon/deepagents_talon/channels/whatsapp.py +++ b/libs/talon/deepagents_talon/channels/whatsapp.py @@ -38,7 +38,13 @@ validate_media, validate_media_size, ) -from deepagents_talon.interfaces import ChannelMedia, ChannelMessage, ChannelStatus, MessageHandler +from deepagents_talon.interfaces import ( + ChannelMedia, + ChannelMessage, + ChannelStatus, + MessageHandler, + SendResult, +) if TYPE_CHECKING: from collections.abc import Mapping @@ -302,22 +308,29 @@ async def stop(self) -> None: await self._stop_bridge() self._status = ChannelStatus(provider="whatsapp", connected=False, detail="disconnected") - async def send_message(self, conversation_id: str, text: str) -> None: + async def send_message(self, conversation_id: str, text: str) -> SendResult: """Send chunked, formatted text to a WhatsApp chat. Args: conversation_id: WhatsApp chat id. text: Message content to send. + + Returns: + Result indicating whether the send succeeded. """ for chunk in _chunk_with_bot_header(text, bot_header=self.config.bot_header): - await self._post_result("/send", {"chatId": conversation_id, "text": chunk}) + response = await self._post_result("/send", {"chatId": conversation_id, "text": chunk}) + return SendResult(success=True, message_id=_extract_message_id(response)) - async def send_media(self, conversation_id: str, media: ChannelMedia) -> None: + async def send_media(self, conversation_id: str, media: ChannelMedia) -> SendResult: """Send validated image or video media to a WhatsApp chat. Args: conversation_id: WhatsApp chat id. media: Media payload to send. + + Returns: + Result indicating whether the send succeeded. """ checked = validate_media( media, @@ -336,7 +349,8 @@ async def send_media(self, conversation_id: str, media: ChannelMedia) -> None: ) else: payload["caption"] = _bot_header(self.config.bot_header) - await self._post_result("/send-media", payload) + response = await self._post_result("/send-media", payload) + return SendResult(success=True, message_id=_extract_message_id(response)) async def send_typing(self, conversation_id: str) -> None: """Send a WhatsApp typing indicator when the bridge supports it. @@ -346,13 +360,16 @@ async def send_typing(self, conversation_id: str) -> None: """ await self._post_result("/typing", {"chatId": conversation_id}) - async def edit_message(self, conversation_id: str, message_id: str, text: str) -> None: + async def edit_message(self, conversation_id: str, message_id: str, text: str) -> SendResult: """Edit a previously sent WhatsApp message. Args: conversation_id: WhatsApp chat id. message_id: Bridge message id. text: Replacement content. + + Returns: + Result indicating whether the edit succeeded. """ await self._post_result( "/edit", @@ -362,6 +379,7 @@ async def edit_message(self, conversation_id: str, message_id: str, text: str) - "content": _with_bot_header(text, bot_header=self.config.bot_header), }, ) + return SendResult(success=True, message_id=message_id) async def status(self) -> ChannelStatus: """Report the most recent bridge connection status.""" @@ -523,6 +541,14 @@ def _with_bot_header(text: str, *, bot_header: str) -> str: return f"{header}\n{format_markdown_for_channel(text)}" +def _extract_message_id(response: object) -> str | None: + if isinstance(response, dict): + value = cast("Mapping[str, object]", response).get("message_id") + if isinstance(value, str) and value: + return value + return None + + def _chunk_with_bot_header(text: str, *, bot_header: str) -> list[str]: header = _bot_header(bot_header) limit = MAX_TEXT_CHARS - len(header) - 1 diff --git a/libs/talon/deepagents_talon/host.py b/libs/talon/deepagents_talon/host.py index 195c2373c9b..afb466a3f0a 100644 --- a/libs/talon/deepagents_talon/host.py +++ b/libs/talon/deepagents_talon/host.py @@ -16,7 +16,7 @@ from types import FrameType from typing import TYPE_CHECKING, cast -from deepagents_talon.channels.base import outbound_media_root_from_env +from deepagents_talon.channels.base import outbound_media_root_from_env, send_with_retry from deepagents_talon.interfaces import ( AgentRequest, AgentResult, @@ -276,7 +276,9 @@ async def deliver_scheduled_result( job: Cron job that produced the result. text: Message text to send. """ - await channel.send_message(job.origin.conversation_id, text) + await send_with_retry( + lambda: channel.send_message(job.origin.conversation_id, text) + ) async def _invoke_agent( self, @@ -331,7 +333,9 @@ async def _start_new_conversation( await self._cancel_conversation_tasks(current_conversation_id) next_reset = self._conversation_resets.get(conversation_root, 0) + 1 self._conversation_resets[conversation_root] = next_reset - await channel.send_message(conversation_id, _NEW_CONVERSATION_MESSAGE) + await send_with_retry( + lambda: channel.send_message(conversation_id, _NEW_CONVERSATION_MESSAGE) + ) async def _cancel_conversation( self, @@ -343,10 +347,14 @@ async def _cancel_conversation( target_conversation_id = reply_conversation_id or conversation_id cancelled = await self._cancel_conversation_tasks(conversation_id) if not cancelled: - await channel.send_message(target_conversation_id, "No in-flight run to stop.") + await send_with_retry( + lambda: channel.send_message(target_conversation_id, "No in-flight run to stop.") + ) return - await channel.send_message(target_conversation_id, "Stopped current run.") + await send_with_retry( + lambda: channel.send_message(target_conversation_id, "Stopped current run.") + ) async def _cancel_conversation_tasks(self, conversation_id: str) -> bool: tasks = { @@ -413,9 +421,11 @@ async def _request_tool_approval( pending = _PendingToolApproval(future=future, sender_id=sender_id) self._pending_tool_approvals[approval.conversation_id] = pending try: - await channel.send_message( - reply_conversation_id, - _format_tool_approval_prompt(approval), + await send_with_retry( + lambda: channel.send_message( + reply_conversation_id, + _format_tool_approval_prompt(approval), + ) ) return await future finally: @@ -429,17 +439,21 @@ async def _handle_tool_approval_reply( pending: _PendingToolApproval, ) -> None: if pending.sender_id is not None and message.sender_id != pending.sender_id: - await channel.send_message( - message.conversation_id, - "Only the operator who started this run can approve or deny it.", + await send_with_retry( + lambda: channel.send_message( + message.conversation_id, + "Only the operator who started this run can approve or deny it.", + ) ) return decision = _parse_tool_approval_reply(message.text) if decision is None: - await channel.send_message( - message.conversation_id, - "Reply `approve` to run the tool call or `deny` to skip it.", + await send_with_retry( + lambda: channel.send_message( + message.conversation_id, + "Reply `approve` to run the tool call or `deny` to skip it.", + ) ) return @@ -455,7 +469,9 @@ async def _deliver_agent_result( cleaned, refs = extract_markdown_media(result.text) if not refs: if result.text: - await channel.send_message(conversation_id, result.text) + await send_with_retry( + lambda: channel.send_message(conversation_id, result.text) + ) return media, failed = _outbound_media_from_refs( @@ -471,11 +487,15 @@ async def _deliver_agent_result( fallback_caption=text, ) if text and not sent_media: - await channel.send_message(conversation_id, text) + await send_with_retry( + lambda: channel.send_message(conversation_id, text) + ) elif send_failed and sent_media: - await channel.send_message( - conversation_id, - f"_(Could not attach: {', '.join(send_failed)}.)_", + await send_with_retry( + lambda: channel.send_message( + conversation_id, + f"_(Could not attach: {', '.join(send_failed)}.)_", + ) ) def _track_conversation_task( @@ -595,11 +615,17 @@ async def _send_channel_media( failed: list[str] = [] for index, item in enumerate(media): payload = _media_with_fallback_caption(item, fallback_caption, is_first=index == 0) - try: - await channel.send_media(conversation_id, payload) + result = await send_with_retry( + lambda p=payload: channel.send_media(conversation_id, p) + ) + if result.success: sent = True - except Exception: # noqa: BLE001 # adapters raise transport-specific failures. - logger.warning("Could not send outbound media: %s", payload.path, exc_info=True) + else: + logger.warning( + "Could not send outbound media: %s (%s)", + payload.path, + result.error, + ) failed.append(payload.caption or payload.path.name) return sent, failed @@ -616,13 +642,8 @@ def _media_with_fallback_caption( async def _send_typing(channel: ChannelAdapter, conversation_id: str) -> None: - send_typing = getattr(channel, "send_typing", None) - if not callable(send_typing): - return try: - result = send_typing(conversation_id) - if isinstance(result, Awaitable): - await result + await channel.send_typing(conversation_id) except Exception: # noqa: BLE001 # typing indicators are best-effort adapter calls. logger.debug("Could not send typing indicator", exc_info=True) diff --git a/libs/talon/deepagents_talon/interfaces.py b/libs/talon/deepagents_talon/interfaces.py index 8bb66a28823..17257479a16 100644 --- a/libs/talon/deepagents_talon/interfaces.py +++ b/libs/talon/deepagents_talon/interfaces.py @@ -58,10 +58,27 @@ class ChannelMedia: """ path: Path - media_type: Literal["image", "video"] + media_type: Literal["image", "video", "document", "audio", "voice"] caption: str | None = None +@dataclass(frozen=True, slots=True) +class SendResult: + """Result of a channel send operation. + + Args: + success: Whether the send completed without error. + message_id: Channel-specific message identifier when available. + error: Human-readable error description on failure. + retryable: Whether a transient failure may succeed on retry. + """ + + success: bool + message_id: str | None = None + error: str | None = None + retryable: bool = False + + ToolApprovalDecision = Literal["approve", "reject"] @@ -139,29 +156,45 @@ def set_message_handler(self, handler: MessageHandler) -> None: handler: Coroutine callback invoked for each inbound channel message. """ - async def send_message(self, conversation_id: str, text: str) -> None: + async def send_message(self, conversation_id: str, text: str) -> SendResult: """Send a message to a conversation. Args: conversation_id: Channel-specific conversation identifier. text: Message content to send. + + Returns: + Result indicating whether the send succeeded. """ - async def send_media(self, conversation_id: str, media: ChannelMedia) -> None: + async def send_media(self, conversation_id: str, media: ChannelMedia) -> SendResult: """Send media to a conversation. Args: conversation_id: Channel-specific conversation identifier. media: Media payload to deliver. + + Returns: + Result indicating whether the send succeeded. """ - async def edit_message(self, conversation_id: str, message_id: str, text: str) -> None: + async def edit_message(self, conversation_id: str, message_id: str, text: str) -> SendResult: """Edit a previously sent channel message. Args: conversation_id: Channel-specific conversation identifier. message_id: Channel-specific message identifier. text: Replacement message content. + + Returns: + Result indicating whether the edit succeeded. + """ + + async def send_typing(self, conversation_id: str) -> None: + """Send a typing indicator to a conversation. + + Args: + conversation_id: Channel-specific conversation identifier. """ async def status(self) -> ChannelStatus: diff --git a/libs/talon/deepagents_talon/media.py b/libs/talon/deepagents_talon/media.py index 3018615cdde..be52007f8d5 100644 --- a/libs/talon/deepagents_talon/media.py +++ b/libs/talon/deepagents_talon/media.py @@ -38,7 +38,7 @@ VIDEO_EXTENSIONS = frozenset({".mp4", ".mov", ".webm", ".3gp", ".m4v"}) ContentBlock = dict[str, object] -OutboundMediaType = Literal["image", "video"] +OutboundMediaType = Literal["image", "video", "document", "audio", "voice"] _MARKDOWN_MEDIA_PATTERN = re.compile(r"!\[([^\]]*)]\(([^)\s]+)\)") _FENCE_PATTERN = re.compile(r"```[\s\S]*?```") diff --git a/libs/talon/tests/conftest.py b/libs/talon/tests/conftest.py index 8499a834e3b..b79f996f805 100644 --- a/libs/talon/tests/conftest.py +++ b/libs/talon/tests/conftest.py @@ -2,7 +2,7 @@ from typing import TYPE_CHECKING -from deepagents_talon.interfaces import ChannelMedia, ChannelMessage, ChannelStatus +from deepagents_talon.interfaces import ChannelMedia, ChannelMessage, ChannelStatus, SendResult if TYPE_CHECKING: from collections.abc import Awaitable, Callable @@ -33,15 +33,21 @@ async def stop(self) -> None: def set_message_handler(self, handler: Callable[[ChannelMessage], Awaitable[None]]) -> None: self.handler = handler - async def send_message(self, conversation_id: str, text: str) -> None: + async def send_message(self, conversation_id: str, text: str) -> SendResult: self.sent.append((conversation_id, text)) + return SendResult(success=True) - async def send_media(self, conversation_id: str, media: ChannelMedia) -> None: + async def send_media(self, conversation_id: str, media: ChannelMedia) -> SendResult: self.media.append((conversation_id, media)) self.sent.append((conversation_id, f"{media.media_type}:{media.path}")) + return SendResult(success=True) - async def edit_message(self, conversation_id: str, message_id: str, text: str) -> None: + async def edit_message(self, conversation_id: str, message_id: str, text: str) -> SendResult: self.sent.append((conversation_id, f"{message_id}:{text}")) + return SendResult(success=True) + + async def send_typing(self, conversation_id: str) -> None: + pass async def status(self) -> ChannelStatus: return self.status_report diff --git a/libs/talon/tests/integration_tests/test_core_flows.py b/libs/talon/tests/integration_tests/test_core_flows.py index d0dff3f2626..175ecd8bd10 100644 --- a/libs/talon/tests/integration_tests/test_core_flows.py +++ b/libs/talon/tests/integration_tests/test_core_flows.py @@ -8,7 +8,13 @@ from deepagents_talon.cron import CronJobStore, CronOrigin, CronSchedule from deepagents_talon.cron.scheduler import PersistentCronScheduler from deepagents_talon.host import TalonHost -from deepagents_talon.interfaces import AgentRequest, AgentResult, ChannelMessage, ChannelStatus +from deepagents_talon.interfaces import ( + AgentRequest, + AgentResult, + ChannelMessage, + ChannelStatus, + SendResult, +) if TYPE_CHECKING: from collections.abc import Awaitable, Callable @@ -28,14 +34,20 @@ async def stop(self) -> None: def set_message_handler(self, handler: Callable[[ChannelMessage], Awaitable[None]]) -> None: self.handler = handler - async def send_message(self, conversation_id: str, text: str) -> None: + async def send_message(self, conversation_id: str, text: str) -> SendResult: self.sent.append((conversation_id, text)) + return SendResult(success=True) - async def send_media(self, conversation_id: str, media: object) -> None: - pass + async def send_media(self, conversation_id: str, media: object) -> SendResult: + del conversation_id, media + return SendResult(success=True) - async def edit_message(self, conversation_id: str, message_id: str, text: str) -> None: - pass + async def edit_message(self, conversation_id: str, message_id: str, text: str) -> SendResult: + del conversation_id, message_id, text + return SendResult(success=True) + + async def send_typing(self, conversation_id: str) -> None: + del conversation_id async def status(self) -> ChannelStatus: return ChannelStatus(provider="memory", connected=True) From c5ab8472d5a63b0ed384fe4c1c9622f2707ba262 Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sun, 21 Jun 2026 19:59:45 -0700 Subject: [PATCH 35/48] style(talon): fix ruff format in whatsapp, host, and media modules --- libs/talon/deepagents_talon/channels/whatsapp.py | 4 +--- libs/talon/deepagents_talon/host.py | 16 ++++------------ libs/talon/deepagents_talon/media.py | 5 +---- 3 files changed, 6 insertions(+), 19 deletions(-) diff --git a/libs/talon/deepagents_talon/channels/whatsapp.py b/libs/talon/deepagents_talon/channels/whatsapp.py index 18a16b80ab2..fd230bf0dd1 100644 --- a/libs/talon/deepagents_talon/channels/whatsapp.py +++ b/libs/talon/deepagents_talon/channels/whatsapp.py @@ -605,9 +605,7 @@ def _parse_message(payload: object) -> ChannelMessage: or values.get("media_urls"), ) media_mime_types = _str_list( - values.get("media_mime_types") - or values.get("mediaMimeTypes") - or values.get("mimeTypes"), + values.get("media_mime_types") or values.get("mediaMimeTypes") or values.get("mimeTypes"), ) message_type = optional_str( values.get("message_type") or values.get("messageType") or values.get("mediaType"), diff --git a/libs/talon/deepagents_talon/host.py b/libs/talon/deepagents_talon/host.py index afb466a3f0a..62cee757169 100644 --- a/libs/talon/deepagents_talon/host.py +++ b/libs/talon/deepagents_talon/host.py @@ -276,9 +276,7 @@ async def deliver_scheduled_result( job: Cron job that produced the result. text: Message text to send. """ - await send_with_retry( - lambda: channel.send_message(job.origin.conversation_id, text) - ) + await send_with_retry(lambda: channel.send_message(job.origin.conversation_id, text)) async def _invoke_agent( self, @@ -469,9 +467,7 @@ async def _deliver_agent_result( cleaned, refs = extract_markdown_media(result.text) if not refs: if result.text: - await send_with_retry( - lambda: channel.send_message(conversation_id, result.text) - ) + await send_with_retry(lambda: channel.send_message(conversation_id, result.text)) return media, failed = _outbound_media_from_refs( @@ -487,9 +483,7 @@ async def _deliver_agent_result( fallback_caption=text, ) if text and not sent_media: - await send_with_retry( - lambda: channel.send_message(conversation_id, text) - ) + await send_with_retry(lambda: channel.send_message(conversation_id, text)) elif send_failed and sent_media: await send_with_retry( lambda: channel.send_message( @@ -615,9 +609,7 @@ async def _send_channel_media( failed: list[str] = [] for index, item in enumerate(media): payload = _media_with_fallback_caption(item, fallback_caption, is_first=index == 0) - result = await send_with_retry( - lambda p=payload: channel.send_media(conversation_id, p) - ) + result = await send_with_retry(lambda p=payload: channel.send_media(conversation_id, p)) if result.success: sent = True else: diff --git a/libs/talon/deepagents_talon/media.py b/libs/talon/deepagents_talon/media.py index be52007f8d5..49441f4c136 100644 --- a/libs/talon/deepagents_talon/media.py +++ b/libs/talon/deepagents_talon/media.py @@ -297,10 +297,7 @@ def _path_from_value(value: object) -> Path | None: def _media_mime_types(metadata: dict[str, object]) -> list[str]: - raw = ( - metadata.get("media_mime_types") - or metadata.get("mime_types") - ) + raw = metadata.get("media_mime_types") or metadata.get("mime_types") if not isinstance(raw, list): return [] return [item for item in raw if isinstance(item, str) and "/" in item] From 09e772a306cf9fcf53d73dca9e45b9aee991cc24 Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Sun, 21 Jun 2026 20:45:54 -0700 Subject: [PATCH 36/48] fix(talon): treat `None` return from legacy channel adapters as success in `send_with_retry` --- libs/talon/deepagents_talon/channels/base.py | 20 +++++++++++--- libs/talon/tests/channels/test_base.py | 28 +++++++++++++++++++- 2 files changed, 44 insertions(+), 4 deletions(-) diff --git a/libs/talon/deepagents_talon/channels/base.py b/libs/talon/deepagents_talon/channels/base.py index 0491abf0f82..1827acf2279 100644 --- a/libs/talon/deepagents_talon/channels/base.py +++ b/libs/talon/deepagents_talon/channels/base.py @@ -523,7 +523,7 @@ def is_retryable_error(error: str | None) -> bool: async def send_with_retry( - send_fn: Callable[[], Awaitable[SendResult]], + send_fn: Callable[[], Awaitable[SendResult | None]], *, max_retries: int = 2, base_delay: float = 2.0, @@ -538,7 +538,7 @@ async def send_with_retry( Returns: The final `SendResult` from the send function. """ - result = await send_fn() + result = _normalize_send_result(await send_fn()) if result.success: return result if not (result.retryable or is_retryable_error(result.error)): @@ -546,9 +546,23 @@ async def send_with_retry( for attempt in range(1, max_retries + 1): delay = base_delay * (2 ** (attempt - 1)) await asyncio.sleep(delay) - result = await send_fn() + result = _normalize_send_result(await send_fn()) if result.success: return result if not (result.retryable or is_retryable_error(result.error)): return result return result + + +def _normalize_send_result(result: SendResult | None) -> SendResult: + """Normalize a send result, treating ``None`` as success for legacy adapters. + + Args: + result: Return value from a channel send method, or ``None``. + + Returns: + The original result, or a success result when the adapter returned ``None``. + """ + if result is None: + return SendResult(success=True) + return result diff --git a/libs/talon/tests/channels/test_base.py b/libs/talon/tests/channels/test_base.py index f99ea10b1cc..437e882392e 100644 --- a/libs/talon/tests/channels/test_base.py +++ b/libs/talon/tests/channels/test_base.py @@ -13,9 +13,10 @@ format_markdown_for_channel, max_media_bytes_from_env, message_with_media_paths, + send_with_retry, validate_media, ) -from deepagents_talon.interfaces import ChannelMedia, ChannelMessage +from deepagents_talon.interfaces import ChannelMedia, ChannelMessage, SendResult def test_default_exposure_allows_only_self_messages() -> None: @@ -157,3 +158,28 @@ def test_max_media_bytes_from_env_accepts_positive_integer() -> None: def test_max_media_bytes_from_env_rejects_invalid_values() -> None: with pytest.raises(ValueError, match="positive integer"): max_media_bytes_from_env({"DEEPAGENTS_TALON_MAX_MEDIA_BYTES": "0"}) + + +async def test_send_with_retry_treats_none_return_as_success() -> None: + async def legacy_send() -> None: + return None + + result = await send_with_retry(legacy_send) + + assert result.success is True + + +async def test_send_with_retry_treats_none_return_as_success_on_retry() -> None: + calls = 0 + + async def flaky_legacy_send() -> None: + nonlocal calls + calls += 1 + if calls == 1: + return SendResult(success=False, error="connection error", retryable=True) + return None + + result = await send_with_retry(flaky_legacy_send, base_delay=0.01) + + assert result.success is True + assert calls == 2 From 0c923e716bb835d2a11855c090dd89c92efc658f Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Mon, 22 Jun 2026 11:13:05 -0700 Subject: [PATCH 37/48] refactor(talon): make module-internal symbols private and unify media size limit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Prefix module-internal symbols with underscore: , , , , , - Remove from - Remove per-type media constants (, in base.py; , , in telegram.py) and — all channels now use a single from config controlled by - Simplify to check only - Update tests to match renamed symbols and use config-based size limit --- .../deepagents_talon/channels/__init__.py | 2 - libs/talon/deepagents_talon/channels/base.py | 17 ++--- .../deepagents_talon/channels/telegram.py | 53 ++++++--------- .../deepagents_talon/channels/whatsapp.py | 40 ++++++------ libs/talon/tests/channels/test_telegram.py | 65 ++++++++++--------- libs/talon/tests/channels/test_whatsapp.py | 34 +++++----- 6 files changed, 98 insertions(+), 113 deletions(-) diff --git a/libs/talon/deepagents_talon/channels/__init__.py b/libs/talon/deepagents_talon/channels/__init__.py index ee888fa5c47..b0a384c331a 100644 --- a/libs/talon/deepagents_talon/channels/__init__.py +++ b/libs/talon/deepagents_talon/channels/__init__.py @@ -9,7 +9,6 @@ ExposureMode, chunk_text, format_markdown_for_channel, - is_retryable_error, send_with_retry, validate_media, ) @@ -26,7 +25,6 @@ "WhatsAppChannelConfig", "chunk_text", "format_markdown_for_channel", - "is_retryable_error", "send_with_retry", "validate_media", ] diff --git a/libs/talon/deepagents_talon/channels/base.py b/libs/talon/deepagents_talon/channels/base.py index 1827acf2279..7edca087f59 100644 --- a/libs/talon/deepagents_talon/channels/base.py +++ b/libs/talon/deepagents_talon/channels/base.py @@ -24,8 +24,6 @@ _T = TypeVar("_T") MAX_TEXT_CHARS = 4096 -MAX_IMAGE_BYTES = 16 * 1024 * 1024 -MAX_VIDEO_BYTES = 64 * 1024 * 1024 DEFAULT_MAX_MEDIA_BYTES = 1024 * 1024 * 1024 MAX_MEDIA_BYTES_ENV = "DEEPAGENTS_TALON_MAX_MEDIA_BYTES" OPEN_EXPOSURE_ACK_VALUE = "allow-arbitrary-senders" @@ -425,12 +423,11 @@ def _validate_media_size( path: Path, max_bytes: int | None = None, ) -> ChannelMedia: - limit = MAX_IMAGE_BYTES if media.media_type == "image" else MAX_VIDEO_BYTES - if max_bytes is not None: - limit = min(limit, max_bytes) + if max_bytes is None: + return ChannelMedia(path=path, media_type=media.media_type, caption=media.caption) size = path.stat().st_size - if size > limit: - msg = f"{media.media_type} media is too large: {size} bytes exceeds {limit}" + if size > max_bytes: + msg = f"{media.media_type} media is too large: {size} bytes exceeds {max_bytes}" raise ChannelMediaError(msg) return ChannelMedia(path=path, media_type=media.media_type, caption=media.caption) @@ -507,7 +504,7 @@ def _media_type(path: Path) -> str: ) -def is_retryable_error(error: str | None) -> bool: +def _is_retryable_error(error: str | None) -> bool: """Return whether an error message looks like a transient network failure. Args: @@ -541,7 +538,7 @@ async def send_with_retry( result = _normalize_send_result(await send_fn()) if result.success: return result - if not (result.retryable or is_retryable_error(result.error)): + if not (result.retryable or _is_retryable_error(result.error)): return result for attempt in range(1, max_retries + 1): delay = base_delay * (2 ** (attempt - 1)) @@ -549,7 +546,7 @@ async def send_with_retry( result = _normalize_send_result(await send_fn()) if result.success: return result - if not (result.retryable or is_retryable_error(result.error)): + if not (result.retryable or _is_retryable_error(result.error)): return result return result diff --git a/libs/talon/deepagents_talon/channels/telegram.py b/libs/talon/deepagents_talon/channels/telegram.py index ad5961a8960..ffa28c7f857 100644 --- a/libs/talon/deepagents_talon/channels/telegram.py +++ b/libs/talon/deepagents_talon/channels/telegram.py @@ -54,16 +54,13 @@ DEFAULT_POLL_TIMEOUT_SECONDS = 30.0 DEFAULT_POLL_INTERVAL_SECONDS = 1.0 DEFAULT_REQUEST_TIMEOUT_SECONDS = 35.0 -MAX_PHOTO_BYTES = 10 * 1024 * 1024 -MAX_DOCUMENT_BYTES = 50 * 1024 * 1024 -MAX_VIDEO_BYTES = 50 * 1024 * 1024 MAX_CAPTION_CHARS = 1024 OPEN_EXPOSURE_ACK_ENV = "DEEPAGENTS_TALON_TELEGRAM_OPEN_ACK" _OFFSET_FILENAME = "telegram_offset.json" _ALLOWED_UPDATES = ["message", "channel_post"] -class TelegramError(RuntimeError): +class _TelegramError(RuntimeError): """Raised when the Telegram Bot API reports or causes a transport error. Args: @@ -190,7 +187,7 @@ def offset_file(self) -> Path: return self.session_dir / _OFFSET_FILENAME -class TelegramTransport: +class _TelegramTransport: """Small HTTP client for the Telegram Bot API.""" def __init__(self, *, api_base: str, token: str, timeout: float) -> None: @@ -216,7 +213,7 @@ async def call(self, method: str, **params: object) -> object: JSON-decoded response body. Raises: - TelegramError: If the request fails or the API returns an error. + _TelegramError: If the request fails or the API returns an error. """ return await asyncio.to_thread(self._request, method, params) @@ -240,7 +237,7 @@ async def upload( JSON-decoded response body. Raises: - TelegramError: If the request fails or the API returns an error. + _TelegramError: If the request fails or the API returns an error. """ return await asyncio.to_thread(self._upload, method, file_field, file_path, params) @@ -290,7 +287,7 @@ def _send_request(self, method: str, request: urllib.request.Request) -> object: payload = json.loads(response.read().decode()) except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as error: msg = f"Telegram Bot API request failed: {method}" - raise TelegramError(msg) from error + raise _TelegramError(msg) from error return _validate_response(payload) @@ -305,7 +302,7 @@ def __init__( self, config: TelegramChannelConfig, *, - transport: TelegramTransport | None = None, + transport: _TelegramTransport | None = None, ) -> None: """Initialize the Telegram channel without starting it. @@ -314,7 +311,7 @@ def __init__( transport: Optional test transport implementing the Bot API. """ self.config = config - self._transport = transport or TelegramTransport( + self._transport = transport or _TelegramTransport( api_base=config.api_base, token=config.bot_token, timeout=config.request_timeout_seconds, @@ -388,11 +385,10 @@ async def send_media(self, conversation_id: str, media: ChannelMedia) -> SendRes Raises: ChannelMediaError: If the media is too large or invalid. """ - telegram_limit = _telegram_media_limit(media.media_type) checked = validate_media( media, root=self.config.outbound_media_dir, - max_bytes=min(self.config.max_media_bytes, telegram_limit), + max_bytes=self.config.max_media_bytes, ) caption = await self._media_caption(conversation_id, checked.caption) method, file_field = _telegram_send_method(checked.media_type) @@ -419,7 +415,7 @@ async def send_typing(self, conversation_id: str) -> None: chat_id=conversation_id, action="typing", ) - except TelegramError: + except _TelegramError: logger.debug("Could not send Telegram typing indicator", exc_info=True) async def edit_message(self, conversation_id: str, message_id: str, text: str) -> SendResult: @@ -448,7 +444,7 @@ async def status(self) -> ChannelStatus: async def _identify_bot(self) -> None: try: payload = await self._transport.call("getMe") - except TelegramError: + except _TelegramError: logger.exception("Telegram getMe failed during startup") self._status = ChannelStatus( provider="telegram", @@ -513,7 +509,7 @@ async def _poll_updates(self) -> None: await dispatch_message(self._handler, message, provider="Telegram") if updates: self._advance_offset(updates) - except TelegramError as error: + except _TelegramError as error: delay = ( error.retry_after if error.retry_after is not None @@ -575,7 +571,7 @@ async def _prepare_inbound_media(self, message: ChannelMessage) -> ChannelMessag media_type=media_type, message_id=message.message_id, ) - except (ChannelMediaError, TelegramError, urllib.error.URLError, TimeoutError) as error: + except (ChannelMediaError, _TelegramError, urllib.error.URLError, TimeoutError) as error: logger.warning( "Skipping Telegram inbound media for message %s: %s", message.message_id, @@ -615,7 +611,7 @@ async def _download_inbound_media( file_path = result.get("file_path") if isinstance(result, dict) else None if not isinstance(file_path, str): msg = "Telegram getFile response missing file_path" - raise TelegramError(msg) + raise _TelegramError(msg) file_size = result.get("file_size") if isinstance(result, dict) else None if isinstance(file_size, int) and file_size > self.config.max_media_bytes: msg = ( @@ -625,7 +621,7 @@ async def _download_inbound_media( raise ChannelMediaError(msg) if self.config.inbound_media_dir is None: msg = "Telegram inbound media directory is not configured" - raise TelegramError(msg) + raise _TelegramError(msg) suffix = _safe_suffix(file_path, media_type) destination = self.config.inbound_media_dir / _inbound_media_filename( message_id=message_id, @@ -643,13 +639,6 @@ async def _download_inbound_media( return destination -def _telegram_media_limit(media_type: str) -> int: - """Return the Telegram Bot API upload size limit for a media type.""" - if media_type == "image": - return MAX_PHOTO_BYTES - return MAX_DOCUMENT_BYTES - - def _telegram_send_method(media_type: str) -> tuple[str, str]: """Return the Bot API method and file field for a media type.""" if media_type == "image": @@ -812,18 +801,18 @@ def _validate_response(payload: object) -> object: The ``result`` field from the response. Raises: - TelegramError: If the response is not an object or reports an error. + _TelegramError: If the response is not an object or reports an error. """ if not isinstance(payload, dict): msg = "Telegram Bot API response must be an object" - raise TelegramError(msg) + raise _TelegramError(msg) values = cast("Mapping[str, object]", payload) if not values.get("ok", True): description = values.get("description", "unknown error") msg = f"Telegram Bot API error: {description}" retry_after_raw = values.get("retry_after") retry_after = float(retry_after_raw) if isinstance(retry_after_raw, (int, float)) else None - raise TelegramError(msg, retry_after=retry_after) + raise _TelegramError(msg, retry_after=retry_after) return values.get("result") @@ -837,11 +826,11 @@ def _extract_result(result: object) -> dict[str, object]: The result object as a dict. Raises: - TelegramError: If the result is not a dict. + _TelegramError: If the result is not a dict. """ if not isinstance(result, dict): msg = "Telegram Bot API response missing result" - raise TelegramError(msg) + raise _TelegramError(msg) return cast("dict[str, object]", result) @@ -864,11 +853,11 @@ def _extract_updates(result: object) -> list[dict[str, object]]: List of update objects. Raises: - TelegramError: If the result is not a list. + _TelegramError: If the result is not a list. """ if not isinstance(result, list): msg = "Telegram getUpdates result must be a list" - raise TelegramError(msg) + raise _TelegramError(msg) return [cast("dict[str, object]", item) for item in result if isinstance(item, dict)] diff --git a/libs/talon/deepagents_talon/channels/whatsapp.py b/libs/talon/deepagents_talon/channels/whatsapp.py index fd230bf0dd1..86fe718958c 100644 --- a/libs/talon/deepagents_talon/channels/whatsapp.py +++ b/libs/talon/deepagents_talon/channels/whatsapp.py @@ -66,7 +66,7 @@ OPEN_EXPOSURE_ACK_ENV = "DEEPAGENTS_TALON_WHATSAPP_OPEN_ACK" -class WhatsAppBridgeError(RuntimeError): +class _WhatsAppBridgeError(RuntimeError): """Raised when the WhatsApp bridge reports or causes a transport error.""" @@ -184,7 +184,7 @@ def base_url(self) -> str: return f"http://{self.host}:{self.port}" -class BridgeTransport: +class _BridgeTransport: """Small JSON HTTP client for the loopback bridge.""" def __init__(self, *, base_url: str, timeout: float, token: str | None = None) -> None: @@ -241,7 +241,7 @@ def _request(self, method: str, path: str, payload: Mapping[str, object] | None) return json.loads(response.read().decode()) except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as error: msg = f"WhatsApp bridge request failed: {method} {path}" - raise WhatsAppBridgeError(msg) from error + raise _WhatsAppBridgeError(msg) from error class WhatsAppChannel: @@ -251,7 +251,7 @@ def __init__( self, config: WhatsAppChannelConfig, *, - transport: BridgeTransport | None = None, + transport: _BridgeTransport | None = None, ) -> None: """Initialize the WhatsApp channel without starting it. @@ -260,7 +260,7 @@ def __init__( transport: Optional test transport implementing the bridge API. """ self.config = config - self._transport = transport or BridgeTransport( + self._transport = transport or _BridgeTransport( base_url=config.base_url, timeout=config.request_timeout_seconds, token=config.bridge_token, @@ -455,7 +455,7 @@ async def _poll_messages(self) -> None: message.message_id, message.conversation_id, ) - except WhatsAppBridgeError: + except _WhatsAppBridgeError: logger.exception("Failed to poll WhatsApp bridge messages") await asyncio.sleep(self.config.poll_interval_seconds) @@ -465,7 +465,7 @@ async def _watch_health(self) -> None: payload = await self._transport.get("/health") self._status = _parse_status(payload) self._failed_health_checks = 0 - except WhatsAppBridgeError: + except _WhatsAppBridgeError: self._failed_health_checks += 1 self._status = ChannelStatus( provider="whatsapp", @@ -478,19 +478,19 @@ async def _watch_health(self) -> None: async def _wait_for_bridge(self) -> None: deadline = asyncio.get_running_loop().time() + DEFAULT_BRIDGE_START_TIMEOUT_SECONDS - last_error: WhatsAppBridgeError | None = None + last_error: _WhatsAppBridgeError | None = None while not self._stopped.is_set(): if self._process is not None and self._process.returncode is not None: msg = f"WhatsApp bridge exited during startup with code {self._process.returncode}" - raise WhatsAppBridgeError(msg) from last_error + raise _WhatsAppBridgeError(msg) from last_error try: payload = await self._transport.get("/health") status = _parse_status(payload) - except WhatsAppBridgeError as error: + except _WhatsAppBridgeError as error: last_error = error if asyncio.get_running_loop().time() >= deadline: msg = "WhatsApp bridge did not become ready before startup timeout" - raise WhatsAppBridgeError(msg) from error + raise _WhatsAppBridgeError(msg) from error await asyncio.sleep(0.2) else: self._status = status @@ -526,7 +526,7 @@ async def _post_result(self, path: str, payload: Mapping[str, object]) -> object if result.get("success") is not False: return response msg = str(result.get("error") or "WhatsApp bridge returned an error") - raise WhatsAppBridgeError(msg) + raise _WhatsAppBridgeError(msg) return response @@ -556,7 +556,7 @@ def _chunk_with_bot_header(text: str, *, bot_header: str) -> list[str]: return [f"{header}\n{chunk}" for chunk in chunks] -def bridge_script_path() -> Path: +def _bridge_script_path() -> Path: """Return the packaged Node bridge script path.""" return Path(str(files("deepagents_talon.channels.whatsapp_bridge").joinpath("bridge.js"))) @@ -582,21 +582,21 @@ def _validate_loopback_url(value: str) -> str: parsed = urllib.parse.urlparse(value) if parsed.scheme != "http" or parsed.hostname not in {"127.0.0.1", "localhost", "::1"}: msg = "WhatsApp bridge URL must use HTTP loopback" - raise WhatsAppBridgeError(msg) + raise _WhatsAppBridgeError(msg) return value def _parse_messages(payload: object) -> list[ChannelMessage]: if not isinstance(payload, list): msg = "WhatsApp bridge /messages response must be a list" - raise WhatsAppBridgeError(msg) + raise _WhatsAppBridgeError(msg) return [_parse_message(item) for item in payload] def _parse_message(payload: object) -> ChannelMessage: if not isinstance(payload, dict): msg = "WhatsApp bridge message must be an object" - raise WhatsAppBridgeError(msg) + raise _WhatsAppBridgeError(msg) values = cast("Mapping[str, object]", payload) media_paths = _str_list( values.get("media_paths") @@ -695,7 +695,7 @@ def _enforce_inbound_media_cap(message: ChannelMessage, *, max_bytes: int) -> Ch def _parse_status(payload: object) -> ChannelStatus: if not isinstance(payload, dict): msg = "WhatsApp bridge /health response must be an object" - raise WhatsAppBridgeError(msg) + raise _WhatsAppBridgeError(msg) values = cast("Mapping[str, object]", payload) detail = _required_str(values, "status") return ChannelStatus( @@ -709,7 +709,7 @@ def _required_str(payload: Mapping[str, object], key: str) -> str: value = payload.get(key) if not isinstance(value, str) or not value: msg = f"WhatsApp bridge payload missing string field: {key}" - raise WhatsAppBridgeError(msg) + raise _WhatsAppBridgeError(msg) return value @@ -720,7 +720,7 @@ def _required_str_any(payload: Mapping[str, object], keys: tuple[str, ...]) -> s return value names = ", ".join(keys) msg = f"WhatsApp bridge payload missing string field: {names}" - raise WhatsAppBridgeError(msg) + raise _WhatsAppBridgeError(msg) def _str_list(value: object) -> list[str]: @@ -768,5 +768,5 @@ def _bridge_command(env: Mapping[str, str]) -> tuple[str, ...] | None: if value: return tuple(shlex.split(value)) if env.get("DEEPAGENTS_TALON_WHATSAPP_START_BRIDGE", "").lower() in {"1", "true", "yes"}: - return ("node", str(bridge_script_path())) + return ("node", str(_bridge_script_path())) return None diff --git a/libs/talon/tests/channels/test_telegram.py b/libs/talon/tests/channels/test_telegram.py index 62754844aae..be9e73a46c0 100644 --- a/libs/talon/tests/channels/test_telegram.py +++ b/libs/talon/tests/channels/test_telegram.py @@ -3,6 +3,7 @@ import asyncio import json import os +from dataclasses import replace from pathlib import Path from typing import Literal, Self, cast @@ -16,16 +17,14 @@ ExposureMode, ) from deepagents_talon.channels.telegram import ( - MAX_PHOTO_BYTES, - MAX_VIDEO_BYTES, TelegramChannel, TelegramChannelConfig, - TelegramError, - TelegramTransport, _download_file, _encode_multipart_form, _load_offset, _save_offset, + _TelegramError, + _TelegramTransport, ) from deepagents_talon.config import TalonConfig from deepagents_talon.interfaces import ChannelMedia, ChannelMessage @@ -106,7 +105,7 @@ async def call(self, method: str, **params: object) -> object: # noqa: ARG002 self.calls += 1 if self.calls == 1: msg = "network error" - raise TelegramError(msg) + raise _TelegramError(msg) return [] return True @@ -388,7 +387,7 @@ async def test_channel_polls_and_dispatches_allowed_messages(tmp_path: Path) -> ) channel = TelegramChannel( _make_config(tmp_path, operator_id="111"), - transport=cast("TelegramTransport", transport), + transport=cast("_TelegramTransport", transport), ) received: list[ChannelMessage] = [] @@ -421,7 +420,7 @@ async def test_channel_polls_and_dispatches_allowed_channel_posts(tmp_path: Path conversations=frozenset({"-100111"}), ), ), - transport=cast("TelegramTransport", transport), + transport=cast("_TelegramTransport", transport), ) received: list[ChannelMessage] = [] @@ -457,7 +456,7 @@ async def test_channel_polls_and_dispatches_allowed_private_users(tmp_path: Path ), allowed_user_ids=frozenset({"111"}), ), - transport=cast("TelegramTransport", transport), + transport=cast("_TelegramTransport", transport), ) received: list[ChannelMessage] = [] @@ -482,7 +481,7 @@ async def test_channel_posts_do_not_pass_self_exposure(tmp_path: Path) -> None: ) channel = TelegramChannel( _make_config(tmp_path, operator_id="111"), - transport=cast("TelegramTransport", transport), + transport=cast("_TelegramTransport", transport), ) received: list[ChannelMessage] = [] @@ -508,7 +507,7 @@ async def test_channel_drops_group_messages(tmp_path: Path) -> None: ) channel = TelegramChannel( _make_config(tmp_path, exposure=ChannelExposure(mode=ExposureMode.OPEN)), - transport=cast("TelegramTransport", transport), + transport=cast("_TelegramTransport", transport), ) received: list[ChannelMessage] = [] @@ -533,7 +532,7 @@ async def test_channel_does_not_trust_private_chat_sender_as_self(tmp_path: Path ) channel = TelegramChannel( _make_config(tmp_path, operator_id="999"), - transport=cast("TelegramTransport", transport), + transport=cast("_TelegramTransport", transport), ) received: list[ChannelMessage] = [] @@ -564,7 +563,7 @@ async def test_channel_survives_transient_polling_error(tmp_path: Path) -> None: ) channel = TelegramChannel( config, - transport=cast("TelegramTransport", transport), + transport=cast("_TelegramTransport", transport), ) await channel.start() @@ -580,7 +579,7 @@ async def test_channel_identifies_bot_on_start(tmp_path: Path) -> None: transport = RecordingTransport() channel = TelegramChannel( _make_config(tmp_path, exposure=ChannelExposure(mode=ExposureMode.OPEN)), - transport=cast("TelegramTransport", transport), + transport=cast("_TelegramTransport", transport), ) await channel.start() @@ -597,7 +596,7 @@ async def test_send_message_uses_plain_text(tmp_path: Path) -> None: transport = RecordingTransport() channel = TelegramChannel( _make_config(tmp_path), - transport=cast("TelegramTransport", transport), + transport=cast("_TelegramTransport", transport), ) await channel.send_message("123", "hello *world*") @@ -613,7 +612,7 @@ async def test_send_message_chunks_long_text(tmp_path: Path) -> None: transport = RecordingTransport() channel = TelegramChannel( _make_config(tmp_path), - transport=cast("TelegramTransport", transport), + transport=cast("_TelegramTransport", transport), ) long_text = "x" * 5000 @@ -632,13 +631,13 @@ def fake_urlopen(request: object, *, timeout: float) -> JsonResponse: # noqa: A return JsonResponse({"ok": False, "description": "bad request"}) monkeypatch.setattr("urllib.request.urlopen", fake_urlopen) - transport = TelegramTransport( + transport = _TelegramTransport( api_base="https://api.telegram.org", token="test-token", # noqa: S106 # inert test token timeout=1, ) - with pytest.raises(TelegramError, match="bad request"): + with pytest.raises(_TelegramError, match="bad request"): await transport.call("sendMessage", chat_id="123", text="hello") @@ -652,13 +651,13 @@ def fake_urlopen(request: object, *, timeout: float) -> JsonResponse: # noqa: A image = tmp_path / "image.png" image.write_bytes(b"image-data") monkeypatch.setattr("urllib.request.urlopen", fake_urlopen) - transport = TelegramTransport( + transport = _TelegramTransport( api_base="https://api.telegram.org", token="test-token", # noqa: S106 # inert test token timeout=1, ) - with pytest.raises(TelegramError, match="upload rejected"): + with pytest.raises(_TelegramError, match="upload rejected"): await transport.upload("sendPhoto", file_field="photo", file_path=image, chat_id="123") @@ -687,7 +686,7 @@ async def test_send_media_uses_expected_upload_method(tmp_path: Path) -> None: path.write_bytes(b"media-data") channel = TelegramChannel( _make_config(tmp_path), - transport=cast("TelegramTransport", transport), + transport=cast("_TelegramTransport", transport), ) await channel.send_media( @@ -704,7 +703,7 @@ async def test_send_media_sends_long_caption_as_text_before_upload(tmp_path: Pat image.write_bytes(b"image-data") channel = TelegramChannel( _make_config(tmp_path), - transport=cast("TelegramTransport", transport), + transport=cast("_TelegramTransport", transport), ) caption = "x" * 1025 @@ -770,19 +769,21 @@ def patched_stat( monkeypatch.setattr(os, "stat", patched_stat) -async def test_send_media_rejects_provider_oversized_files( +async def test_send_media_rejects_oversized_files( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: cases: tuple[tuple[str, Literal["image", "video"], int], ...] = ( - ("big.png", "image", MAX_PHOTO_BYTES + 1), - ("big.mp4", "video", MAX_VIDEO_BYTES + 1), + ("big.png", "image", 11), + ("big.mp4", "video", 11), ) + config = _make_config(tmp_path) + config = replace(config, max_media_bytes=10) for filename, media_type, fake_size in cases: path = tmp_path / filename path.write_bytes(b"x") - channel = TelegramChannel(_make_config(tmp_path)) + channel = TelegramChannel(config) with monkeypatch.context() as patch: _patch_file_size(patch, path, fake_size) @@ -800,7 +801,7 @@ async def test_edit_message_uses_plain_text(tmp_path: Path) -> None: transport = RecordingTransport() channel = TelegramChannel( _make_config(tmp_path), - transport=cast("TelegramTransport", transport), + transport=cast("_TelegramTransport", transport), ) await channel.edit_message("123", "42", "updated *text*") @@ -875,7 +876,7 @@ async def test_channel_parses_inbound_media( transport = RecordingTransport(updates=[update]) channel = TelegramChannel( _make_config(case_dir, operator_id="111"), - transport=cast("TelegramTransport", transport), + transport=cast("_TelegramTransport", transport), ) received = await _run_channel_once(channel) @@ -934,7 +935,7 @@ async def call(self, method: str, **params: object) -> object: poll_timeout_seconds=1, max_media_bytes=10, ) - channel = TelegramChannel(config, transport=cast("TelegramTransport", transport)) + channel = TelegramChannel(config, transport=cast("_TelegramTransport", transport)) received: list[ChannelMessage] = [] async def record(message: ChannelMessage) -> None: @@ -1022,7 +1023,7 @@ async def test_channel_persists_offset_after_polling(tmp_path: Path) -> None: ], ) config = _make_config(tmp_path, operator_id="111") - channel = TelegramChannel(config, transport=cast("TelegramTransport", transport)) + channel = TelegramChannel(config, transport=cast("_TelegramTransport", transport)) await channel.start() await asyncio.sleep(0) @@ -1039,7 +1040,7 @@ async def test_channel_loads_persisted_offset_on_start(tmp_path: Path) -> None: transport = RecordingTransport( updates=[_make_update(update_id=101, chat_id=111, sender_id=111, text="msg1")], ) - channel = TelegramChannel(config, transport=cast("TelegramTransport", transport)) + channel = TelegramChannel(config, transport=cast("_TelegramTransport", transport)) await channel.start() await asyncio.sleep(0) @@ -1056,7 +1057,7 @@ async def call(self, method: str, **params: object) -> object: if method == "getFile": self.calls.append((method, dict(params))) msg = "temporary getFile failure" - raise TelegramError(msg) + raise _TelegramError(msg) return await super().call(method, **params) transport = FailingGetFileTransport( @@ -1072,7 +1073,7 @@ async def call(self, method: str, **params: object) -> object: ], ) config = _make_config(tmp_path, operator_id="111") - channel = TelegramChannel(config, transport=cast("TelegramTransport", transport)) + channel = TelegramChannel(config, transport=cast("_TelegramTransport", transport)) received: list[ChannelMessage] = [] async def record(message: ChannelMessage) -> None: diff --git a/libs/talon/tests/channels/test_whatsapp.py b/libs/talon/tests/channels/test_whatsapp.py index 028b5db4020..5e0f41dd2cb 100644 --- a/libs/talon/tests/channels/test_whatsapp.py +++ b/libs/talon/tests/channels/test_whatsapp.py @@ -15,11 +15,11 @@ ) from deepagents_talon.channels.whatsapp import ( DEFAULT_WHATSAPP_MAX_MEDIA_BYTES, - BridgeTransport, - WhatsAppBridgeError, WhatsAppChannel, WhatsAppChannelConfig, - bridge_script_path, + _bridge_script_path, + _BridgeTransport, + _WhatsAppBridgeError, ) from deepagents_talon.config import TalonConfig from deepagents_talon.interfaces import ChannelMedia, ChannelMessage @@ -57,7 +57,7 @@ async def get(self, path: str) -> object: self.calls += 1 if self.calls == 1: msg = "bridge not listening yet" - raise WhatsAppBridgeError(msg) + raise _WhatsAppBridgeError(msg) return {"status": "qr_pending", "botId": None} @@ -180,7 +180,7 @@ def fake_urlopen(request: object, *, timeout: float) -> JsonResponse: return JsonResponse() monkeypatch.setattr("urllib.request.urlopen", fake_urlopen) - transport = BridgeTransport( + transport = _BridgeTransport( base_url="http://127.0.0.1:3000", timeout=2, token="test-token", # noqa: S106 # inert test token @@ -248,7 +248,7 @@ async def test_channel_polls_and_dispatches_allowed_messages(tmp_path: Path) -> poll_interval_seconds=60, health_interval_seconds=60, ), - transport=cast("BridgeTransport", transport), + transport=cast("_BridgeTransport", transport), ) received: list[ChannelMessage] = [] @@ -291,7 +291,7 @@ async def test_channel_polls_self_messages_without_operator_id(tmp_path: Path) - poll_interval_seconds=60, health_interval_seconds=60, ), - transport=cast("BridgeTransport", transport), + transport=cast("_BridgeTransport", transport), ) received: list[ChannelMessage] = [] @@ -333,7 +333,7 @@ async def test_channel_parses_inbound_media_payload(tmp_path: Path) -> None: poll_interval_seconds=60, health_interval_seconds=60, ), - transport=cast("BridgeTransport", transport), + transport=cast("_BridgeTransport", transport), ) received: list[ChannelMessage] = [] @@ -378,7 +378,7 @@ async def test_channel_filters_oversized_inbound_media_payload(tmp_path: Path) - poll_interval_seconds=60, health_interval_seconds=60, ), - transport=cast("BridgeTransport", transport), + transport=cast("_BridgeTransport", transport), ) received: list[ChannelMessage] = [] @@ -418,7 +418,7 @@ async def test_channel_normalizes_ptt_payload_as_voice(tmp_path: Path) -> None: poll_interval_seconds=60, health_interval_seconds=60, ), - transport=cast("BridgeTransport", transport), + transport=cast("_BridgeTransport", transport), ) received: list[ChannelMessage] = [] @@ -457,7 +457,7 @@ async def test_channel_normalizes_audio_mime_payload_as_voice(tmp_path: Path) -> poll_interval_seconds=60, health_interval_seconds=60, ), - transport=cast("BridgeTransport", transport), + transport=cast("_BridgeTransport", transport), ) received: list[ChannelMessage] = [] @@ -478,7 +478,7 @@ async def test_channel_sends_chunked_formatted_text(tmp_path: Path) -> None: transport = RecordingTransport() channel = WhatsAppChannel( WhatsAppChannelConfig(session_dir=tmp_path), - transport=cast("BridgeTransport", transport), + transport=cast("_BridgeTransport", transport), ) await channel.send_message("chat", "**bold** " + ("x" * 4096)) @@ -499,7 +499,7 @@ async def test_channel_sends_media_and_edits_messages(tmp_path: Path) -> None: media_dir = tmp_path / "bridge-media" channel = WhatsAppChannel( WhatsAppChannelConfig(session_dir=tmp_path, inbound_media_dir=media_dir), - transport=cast("BridgeTransport", transport), + transport=cast("_BridgeTransport", transport), ) await channel.send_media( @@ -539,7 +539,7 @@ async def test_channel_rejects_media_outside_configured_outbound_root(tmp_path: outside.write_bytes(b"image") channel = WhatsAppChannel( WhatsAppChannelConfig(session_dir=tmp_path, outbound_media_dir=root), - transport=cast("BridgeTransport", transport), + transport=cast("_BridgeTransport", transport), ) with pytest.raises(ChannelMediaError, match="escapes outbound root"): @@ -593,7 +593,7 @@ async def test_channel_waits_for_bridge_health_before_polling(tmp_path: Path) -> transport = DelayedHealthTransport() channel = WhatsAppChannel( WhatsAppChannelConfig(session_dir=tmp_path), - transport=cast("BridgeTransport", transport), + transport=cast("_BridgeTransport", transport), ) await channel._wait_for_bridge() @@ -619,5 +619,5 @@ async def test_channel_forwards_bridge_output_to_logs( def test_bridge_script_is_packaged() -> None: - assert bridge_script_path().name == "bridge.js" - assert bridge_script_path().is_file() + assert _bridge_script_path().name == "bridge.js" + assert _bridge_script_path().is_file() From 34868dda922950ecf9d6ef742dab518c081313bf Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Mon, 22 Jun 2026 11:43:06 -0700 Subject: [PATCH 38/48] fix(talon): catch transport exceptions in send_with_retry send_with_retry only handled SendResult failures, not exceptions. Both built-in adapters can raise from their transport paths (_TelegramError, _WhatsAppBridgeError), so an upload/send failure escaped _send_channel_media and aborted the channel task instead of adding the item to failed and delivering the text fallback. Wrap each send_fn call in _safe_send, which catches exceptions and converts them to failed SendResult objects (retryable=True). This keeps media delivery failures non-fatal at every call site, not just _send_channel_media. Add tests verifying exception-to-SendResult conversion and retry after exception. --- libs/talon/deepagents_talon/channels/base.py | 26 ++++++++++++++++-- libs/talon/tests/channels/test_base.py | 29 ++++++++++++++++++++ 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/libs/talon/deepagents_talon/channels/base.py b/libs/talon/deepagents_talon/channels/base.py index 7edca087f59..e0bdf6825ea 100644 --- a/libs/talon/deepagents_talon/channels/base.py +++ b/libs/talon/deepagents_talon/channels/base.py @@ -527,6 +527,12 @@ async def send_with_retry( ) -> SendResult: """Call a channel send function with automatic retry on transient errors. + Exceptions raised by ``send_fn`` are caught and converted to failed + `SendResult` objects so that transport-level failures remain non-fatal + to the caller. Retryable exceptions (matching the same transient-network + patterns used for `SendResult.error`) are retried like any other + retryable failure. + Args: send_fn: Zero-argument coroutine that performs the actual send. max_retries: Maximum number of retry attempts after the first failure. @@ -535,7 +541,7 @@ async def send_with_retry( Returns: The final `SendResult` from the send function. """ - result = _normalize_send_result(await send_fn()) + result = _normalize_send_result(await _safe_send(send_fn)) if result.success: return result if not (result.retryable or _is_retryable_error(result.error)): @@ -543,7 +549,7 @@ async def send_with_retry( for attempt in range(1, max_retries + 1): delay = base_delay * (2 ** (attempt - 1)) await asyncio.sleep(delay) - result = _normalize_send_result(await send_fn()) + result = _normalize_send_result(await _safe_send(send_fn)) if result.success: return result if not (result.retryable or _is_retryable_error(result.error)): @@ -551,6 +557,22 @@ async def send_with_retry( return result +async def _safe_send(send_fn: Callable[[], Awaitable[SendResult | None]]) -> SendResult | None: + """Call ``send_fn`` and convert exceptions to failed `SendResult` objects. + + Args: + send_fn: Zero-argument coroutine that performs the actual send. + + Returns: + The `SendResult` from ``send_fn``, or a failed `SendResult` when an + exception was raised. + """ + try: + return await send_fn() + except Exception as exc: # noqa: BLE001 # transport errors must not crash the host loop + return SendResult(success=False, error=str(exc) or repr(exc), retryable=True) + + def _normalize_send_result(result: SendResult | None) -> SendResult: """Normalize a send result, treating ``None`` as success for legacy adapters. diff --git a/libs/talon/tests/channels/test_base.py b/libs/talon/tests/channels/test_base.py index 437e882392e..d83c7bff6e6 100644 --- a/libs/talon/tests/channels/test_base.py +++ b/libs/talon/tests/channels/test_base.py @@ -183,3 +183,32 @@ async def flaky_legacy_send() -> None: assert result.success is True assert calls == 2 + + +async def test_send_with_retry_converts_exception_to_failed_result() -> None: + async def raising_send() -> SendResult: + msg = "transport crashed" + raise RuntimeError(msg) + + result = await send_with_retry(raising_send, max_retries=0) + + assert result.success is False + assert "transport crashed" in (result.error or "") + assert result.retryable is True + + +async def test_send_with_retry_retries_after_exception() -> None: + calls = 0 + + async def flaky_send() -> SendResult: + nonlocal calls + calls += 1 + if calls == 1: + msg = "connection reset" + raise RuntimeError(msg) + return SendResult(success=True) + + result = await send_with_retry(flaky_send, max_retries=2, base_delay=0.01) + + assert result.success is True + assert calls == 2 From 2180ccd29426386e1bf5692519bcd3b33b57bc05 Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Mon, 22 Jun 2026 14:16:05 -0700 Subject: [PATCH 39/48] reorg --- examples/{talon-whatsapp => talon}/.env.example | 0 examples/{talon-whatsapp => talon}/AGENTS.md | 0 examples/{talon-whatsapp => talon}/Dockerfile | 0 examples/{talon-whatsapp => talon}/README.md | 0 examples/{talon-whatsapp => talon}/docker-compose.yml | 6 +++--- 5 files changed, 3 insertions(+), 3 deletions(-) rename examples/{talon-whatsapp => talon}/.env.example (100%) rename examples/{talon-whatsapp => talon}/AGENTS.md (100%) rename examples/{talon-whatsapp => talon}/Dockerfile (100%) rename examples/{talon-whatsapp => talon}/README.md (100%) rename examples/{talon-whatsapp => talon}/docker-compose.yml (85%) diff --git a/examples/talon-whatsapp/.env.example b/examples/talon/.env.example similarity index 100% rename from examples/talon-whatsapp/.env.example rename to examples/talon/.env.example diff --git a/examples/talon-whatsapp/AGENTS.md b/examples/talon/AGENTS.md similarity index 100% rename from examples/talon-whatsapp/AGENTS.md rename to examples/talon/AGENTS.md diff --git a/examples/talon-whatsapp/Dockerfile b/examples/talon/Dockerfile similarity index 100% rename from examples/talon-whatsapp/Dockerfile rename to examples/talon/Dockerfile diff --git a/examples/talon-whatsapp/README.md b/examples/talon/README.md similarity index 100% rename from examples/talon-whatsapp/README.md rename to examples/talon/README.md diff --git a/examples/talon-whatsapp/docker-compose.yml b/examples/talon/docker-compose.yml similarity index 85% rename from examples/talon-whatsapp/docker-compose.yml rename to examples/talon/docker-compose.yml index 73d09d6ed2d..4b42b618a0c 100644 --- a/examples/talon-whatsapp/docker-compose.yml +++ b/examples/talon/docker-compose.yml @@ -2,8 +2,8 @@ services: talon: build: context: ../.. - dockerfile: examples/talon-whatsapp/Dockerfile - image: deepagents-talon-whatsapp:local + dockerfile: examples/talon/Dockerfile + image: deepagents-talon:local working_dir: /workspace env_file: - .env @@ -14,7 +14,7 @@ services: DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_ENABLED: ${DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_ENABLED:-true} DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_DEVICE: ${DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_DEVICE:-cpu} volumes: - - ${HOME}/agent-workspace:/workspace + - ${HOME}/talon-workspace:/workspace command: > bash -c " mkdir -p /workspace/.deepagents/$${AGENT_ASSISTANT_ID}/agent && From 05f32067b762d17f8063cdc0346de0086cb3e1eb Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Mon, 22 Jun 2026 15:25:26 -0700 Subject: [PATCH 40/48] refactor(talon): generalize example for both WhatsApp and Telegram channels Remove WhatsApp-specific shared config from .env.example and docker-compose.yml. Both channel configs are now commented-out templates the operator enables via env vars. ASR (voice transcription) defaults to enabled. The Dockerfile COPY path and CMD are updated to drop the talon-whatsapp reference and --whatsapp flag. README is rewritten to cover both channels with separate setup and exposure reference sections. --- examples/talon/.env.example | 33 ++++++++++++++++--------- examples/talon/Dockerfile | 4 +-- examples/talon/README.md | 41 +++++++++++++++++++++++-------- examples/talon/docker-compose.yml | 3 +-- 4 files changed, 56 insertions(+), 25 deletions(-) diff --git a/examples/talon/.env.example b/examples/talon/.env.example index 494323b64b7..8c49ac54258 100644 --- a/examples/talon/.env.example +++ b/examples/talon/.env.example @@ -1,5 +1,5 @@ # Required assistant identity and model. -AGENT_ASSISTANT_ID=whatsapp-local +AGENT_ASSISTANT_ID=talon-local AGENT_MODEL=openai:gpt-5.2 DEEPAGENTS_TALON_CONTEXT_SIZE=75000 OPENAI_API_KEY= @@ -9,17 +9,28 @@ LANGSMITH_TRACING=false LANGSMITH_API_KEY= LANGSMITH_PROJECT=deepagents-talon -# WhatsApp channel. -DEEPAGENTS_TALON_WHATSAPP_ENABLED=true -DEEPAGENTS_TALON_WHATSAPP_EXPOSURE=self -DEEPAGENTS_TALON_WHATSAPP_OPERATOR_ID= -DEEPAGENTS_TALON_WHATSAPP_ALLOWLIST_CHATS= -DEEPAGENTS_TALON_WHATSAPP_MENTION_PATTERNS= -DEEPAGENTS_TALON_WHATSAPP_BRIDGE_HOST=127.0.0.1 -DEEPAGENTS_TALON_WHATSAPP_BRIDGE_PORT=3000 -DEEPAGENTS_TALON_WHATSAPP_START_BRIDGE=true - # Voice transcription. # Uses local NVIDIA Parakeet through Transformers. First use downloads the model. DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_ENABLED=true DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_DEVICE=cpu + +# --- WhatsApp channel --- +# Uncomment to enable the WhatsApp channel adapter. +# DEEPAGENTS_TALON_WHATSAPP_ENABLED=true +# DEEPAGENTS_TALON_WHATSAPP_EXPOSURE=self +# DEEPAGENTS_TALON_WHATSAPP_OPERATOR_ID= +# DEEPAGENTS_TALON_WHATSAPP_ALLOWLIST_CHATS= +# DEEPAGENTS_TALON_WHATSAPP_MENTION_PATTERNS= +# DEEPAGENTS_TALON_WHATSAPP_BRIDGE_HOST=127.0.0.1 +# DEEPAGENTS_TALON_WHATSAPP_BRIDGE_PORT=3000 +# DEEPAGENTS_TALON_WHATSAPP_START_BRIDGE=true + +# --- Telegram channel --- +# Uncomment to enable the Telegram channel adapter. +# DEEPAGENTS_TALON_TELEGRAM_ENABLED=true +# DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN= +# DEEPAGENTS_TALON_TELEGRAM_EXPOSURE=self +# DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID= +# DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_CHATS= +# DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_USERS= +# DEEPAGENTS_TALON_TELEGRAM_MENTION_PATTERNS= diff --git a/examples/talon/Dockerfile b/examples/talon/Dockerfile index a167a2708ab..3b2440bbbd2 100644 --- a/examples/talon/Dockerfile +++ b/examples/talon/Dockerfile @@ -48,7 +48,7 @@ WORKDIR /opt/deepagents-src COPY libs/deepagents ./libs/deepagents COPY libs/code ./libs/code COPY libs/talon ./libs/talon -COPY examples/talon-whatsapp/AGENTS.md /opt/deepagents-talon/AGENTS.md +COPY examples/talon/AGENTS.md /opt/deepagents-talon/AGENTS.md RUN mkdir -p /opt/whatsapp-bridge && \ cp libs/talon/deepagents_talon/channels/whatsapp_bridge/package.json \ @@ -60,4 +60,4 @@ RUN cd libs/talon && uv sync --frozen --extra speech WORKDIR /workspace -CMD ["/opt/deepagents-talon-venv/bin/deepagents-talon", "--whatsapp"] +CMD ["/opt/deepagents-talon-venv/bin/deepagents-talon"] diff --git a/examples/talon/README.md b/examples/talon/README.md index 3ef5db494d2..658b6a3734d 100644 --- a/examples/talon/README.md +++ b/examples/talon/README.md @@ -1,6 +1,6 @@ -# Talon WhatsApp Example +# Talon Example -This example runs one Talon host process with the WhatsApp bridge subprocess in the same container. The bridge binds to loopback inside the container and the host `~/agent-workspace/` directory is mounted at `/workspace`. +This example runs a Talon host process with one or more channel adapters in the same container. The host `~/talon-workspace/` directory is mounted at `/workspace`. > **Experimental:** Talon is an experimental runtime and is subject to change or removal at any time. @@ -8,17 +8,26 @@ This example runs one Talon host process with the WhatsApp bridge subprocess in ```bash cp .env.example .env -mkdir -p ~/agent-workspace -# Fill AGENT_MODEL provider credentials, then build once and run: +mkdir -p ~/talon-workspace +# Fill AGENT_MODEL provider credentials, then uncomment the channel you want to use. +# Build once and run: docker compose build docker compose up ``` -Scan the QR code printed by the bridge. The default exposure mode is `self`, so only messages sent by the paired WhatsApp account trigger the agent. Use `allowlist` or `open` only when you intentionally want other chats to trigger the agent. +### WhatsApp -Voice transcription is enabled in `.env.example`. The Docker example installs `ffmpeg` and the Talon `speech` extra so inbound WhatsApp voice notes are transcribed locally with NVIDIA Parakeet through Transformers before reaching the agent. The first voice message can be slow because the ASR model is downloaded lazily. Set `DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_DEVICE=cuda` when running on a GPU-enabled host. +Uncomment the WhatsApp env vars in `.env` and scan the QR code printed by the bridge. The default exposure mode is `self`, so only messages sent by the paired WhatsApp account trigger the agent. Use `allowlist` or `open` only when you intentionally want other chats to trigger the agent. -Cron records, downloaded inbound media, and WhatsApp session state persist under `~/agent-workspace/.deepagents/`. The agent's default working directory is `/workspace`, so files it creates are written into `~/agent-workspace/` on the host. +### Telegram + +Uncomment the Telegram env vars in `.env` and set `DEEPAGENTS_TALON_TELEGRAM_BOT_TOKEN`. The default exposure mode is `self`, which requires `DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID` to identify your Telegram user ID. Use `allowlist` or `open` only when you intentionally want other chats to trigger the agent. + +## Voice Transcription + +Voice transcription is enabled by default in `.env.example`. The Docker example installs `ffmpeg` and the Talon `speech` extra so inbound voice notes are transcribed locally with NVIDIA Parakeet through Transformers before reaching the agent. The first voice message can be slow because the ASR model is downloaded lazily. Set `DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_DEVICE=cuda` when running on a GPU-enabled host. + +Cron records, downloaded inbound media, and channel session state persist under `~/talon-workspace/.deepagents/`. The agent's default working directory is `/workspace`, so files it creates are written into `~/talon-workspace/` on the host. The image installs the Talon package at build time. Rebuild after changing the Dockerfile, system packages, Node dependencies, or Talon Python dependencies. @@ -35,16 +44,22 @@ npm install cd ../../../.. uv sync --directory libs/talon --extra speech -cp examples/talon-whatsapp/AGENTS.md ~/.deepagents/whatsapp-local/agent/AGENTS.md -export DEEPAGENTS_TALON_WORKSPACE=~/agent-workspace +cp examples/talon/AGENTS.md ~/.deepagents/talon-local/agent/AGENTS.md +export DEEPAGENTS_TALON_WORKSPACE=~/talon-workspace uv run --directory libs/talon deepagents-talon --whatsapp ``` +For Telegram, use `--telegram` instead of `--whatsapp`: + +```bash +uv run --directory libs/talon deepagents-talon --telegram +``` + ## Environment Reference `AGENT_ASSISTANT_ID` names the local state directory under `~/.deepagents/`. `AGENT_MODEL` selects the Deep Agents chat model. If it is unset, Talon runs the echo runtime for smoke tests. -The Docker example overrides `DEEPAGENTS_TALON_HOME` to `/workspace/.deepagents`, so cron jobs are stored at `~/agent-workspace/.deepagents//cron/jobs.json`. Assistant Markdown image/video attachments must use relative paths inside `DEEPAGENTS_TALON_OUTBOUND_MEDIA_DIR`, or inside `DEEPAGENTS_TALON_WORKSPACE` when no outbound media directory is configured. +The Docker example overrides `DEEPAGENTS_TALON_HOME` to `/workspace/.deepagents`, so cron jobs are stored at `~/talon-workspace/.deepagents//cron/jobs.json`. Assistant Markdown image/video attachments must use relative paths inside `DEEPAGENTS_TALON_OUTBOUND_MEDIA_DIR`, or inside `DEEPAGENTS_TALON_WORKSPACE` when no outbound media directory is configured. Set `LANGSMITH_TRACING=true` and `LANGSMITH_API_KEY` to trace each channel or cron-triggered run. `LANGSMITH_PROJECT` defaults to `deepagents-talon`. @@ -54,6 +69,12 @@ WhatsApp exposure: - `DEEPAGENTS_TALON_WHATSAPP_EXPOSURE=allowlist` allows chats in `DEEPAGENTS_TALON_WHATSAPP_ALLOWLIST_CHATS` or messages matching `DEEPAGENTS_TALON_WHATSAPP_MENTION_PATTERNS`. - `DEEPAGENTS_TALON_WHATSAPP_EXPOSURE=open` allows every inbound WhatsApp message. +Telegram exposure: + +- `DEEPAGENTS_TALON_TELEGRAM_EXPOSURE=self` allows only messages from the operator ID set in `DEEPAGENTS_TALON_TELEGRAM_OPERATOR_ID`. +- `DEEPAGENTS_TALON_TELEGRAM_EXPOSURE=allowlist` allows chats in `DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_CHATS`, users in `DEEPAGENTS_TALON_TELEGRAM_ALLOWLIST_USERS`, or messages matching `DEEPAGENTS_TALON_TELEGRAM_MENTION_PATTERNS`. +- `DEEPAGENTS_TALON_TELEGRAM_EXPOSURE=open` allows every inbound Telegram message. + Cron jobs are stored in the assistant state directory at `cron/jobs.json`. Scheduler ticks, dispatch, success/failure, and delivery outcomes are logged as `talon_event` JSON records. ## Resources diff --git a/examples/talon/docker-compose.yml b/examples/talon/docker-compose.yml index 4b42b618a0c..f9f2ae90daf 100644 --- a/examples/talon/docker-compose.yml +++ b/examples/talon/docker-compose.yml @@ -10,7 +10,6 @@ services: environment: DEEPAGENTS_TALON_HOME: /workspace/.deepagents DEEPAGENTS_TALON_WORKSPACE: /workspace - DEEPAGENTS_TALON_WHATSAPP_SESSION_DIR: /workspace/.deepagents/whatsapp-session DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_ENABLED: ${DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_ENABLED:-true} DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_DEVICE: ${DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_DEVICE:-cpu} volumes: @@ -19,5 +18,5 @@ services: bash -c " mkdir -p /workspace/.deepagents/$${AGENT_ASSISTANT_ID}/agent && cp /opt/deepagents-talon/AGENTS.md /workspace/.deepagents/$${AGENT_ASSISTANT_ID}/agent/AGENTS.md && - /opt/deepagents-talon-venv/bin/deepagents-talon --whatsapp + /opt/deepagents-talon-venv/bin/deepagents-talon " From 9168207e0789a4c5dd6059734c26f2be99b9d74e Mon Sep 17 00:00:00 2001 From: John Kennedy <65985482+jkennedyvz@users.noreply.github.com> Date: Mon, 22 Jun 2026 15:51:28 -0700 Subject: [PATCH 41/48] Update libs/talon/deepagents_talon/channels/base.py Co-authored-by: Mason Daugherty Signed-off-by: John Kennedy <65985482+jkennedyvz@users.noreply.github.com> --- libs/talon/deepagents_talon/channels/base.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libs/talon/deepagents_talon/channels/base.py b/libs/talon/deepagents_talon/channels/base.py index e0bdf6825ea..015889c91b7 100644 --- a/libs/talon/deepagents_talon/channels/base.py +++ b/libs/talon/deepagents_talon/channels/base.py @@ -56,7 +56,7 @@ class ChannelExposureEnv: Args: provider: Human-readable provider name used in error messages. - env_prefix: Prefix for exposure env vars (e.g. ``DEEPAGENTS_TALON_TELEGRAM``). + env_prefix: Prefix for exposure env vars (e.g. `DEEPAGENTS_TALON_TELEGRAM`). open_ack: Environment variable acknowledging open-exposure risk. open_ack_value: Required acknowledgement value for open exposure. require_self_operator: Whether `self` exposure requires an operator id. From 9abbc5fe4909717425170ef0253c60a8b97d0c24 Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Mon, 22 Jun 2026 15:53:44 -0700 Subject: [PATCH 42/48] refactor(talon): move dataclass Args blocks to attribute docstrings Mason's feedback (PR #4097 discussion_r3455630256): move the ChannelExposureEnv and ChannelExposure Args blocks to attribute-level docstring form so ref-doc parsers (griffe/mkdocstrings) pick them up as field documentation rather than only as constructor params. Also applies the nit on env_prefix (single backticks per project docstring convention). --- libs/talon/deepagents_talon/channels/base.py | 36 ++++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/libs/talon/deepagents_talon/channels/base.py b/libs/talon/deepagents_talon/channels/base.py index 015889c91b7..c523088928f 100644 --- a/libs/talon/deepagents_talon/channels/base.py +++ b/libs/talon/deepagents_talon/channels/base.py @@ -52,39 +52,39 @@ class ChannelMediaError(ValueError): @dataclass(frozen=True, slots=True) class ChannelExposureEnv: - """Environment variable prefix and options for channel exposure policy. - - Args: - provider: Human-readable provider name used in error messages. - env_prefix: Prefix for exposure env vars (e.g. `DEEPAGENTS_TALON_TELEGRAM`). - open_ack: Environment variable acknowledging open-exposure risk. - open_ack_value: Required acknowledgement value for open exposure. - require_self_operator: Whether `self` exposure requires an operator id. - """ + """Environment variable prefix and options for channel exposure policy.""" provider: str + """Human-readable provider name used in error messages.""" + env_prefix: str + """Prefix for exposure env vars (e.g. `DEEPAGENTS_TALON_TELEGRAM`).""" + open_ack: str + """Environment variable acknowledging open-exposure risk.""" + open_ack_value: str = OPEN_EXPOSURE_ACK_VALUE + """Required acknowledgement value for open exposure.""" + require_self_operator: bool = False + """Whether `self` exposure requires an operator id.""" @dataclass(frozen=True, slots=True) class ChannelExposure: - """Inbound exposure policy shared by channel adapters. - - Args: - mode: Trigger policy for inbound messages. - conversations: Conversation ids allowed in allowlist mode. - mention_patterns: Glob-style patterns that may allow a message by text. - operator_ids: Channel-specific ids for operator accounts that may trigger - `self` exposure. - """ + """Inbound exposure policy shared by channel adapters.""" mode: ExposureMode = ExposureMode.SELF + """Trigger policy for inbound messages.""" + conversations: frozenset[str] = field(default_factory=frozenset) + """Conversation ids allowed in allowlist mode.""" + mention_patterns: tuple[str, ...] = () + """Glob-style patterns that may allow a message by text.""" + operator_ids: frozenset[str] = field(default_factory=frozenset) + """Channel-specific ids for operator accounts that may trigger `self` exposure.""" def allows(self, message: ChannelMessage) -> bool: """Return whether an inbound message may trigger the agent. From 8e4e07669cf7d6f991f4b5f9b6dd93835eb266f8 Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Mon, 22 Jun 2026 17:23:09 -0700 Subject: [PATCH 43/48] fix(talon): preserve agent memory across container restarts Use cp -n (no-clobber) so the AGENTS.md template is only seeded on first run. Previously, cp overwrote the agent's accumulated memory with the template on every container start. --- examples/talon/docker-compose.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/talon/docker-compose.yml b/examples/talon/docker-compose.yml index f9f2ae90daf..f70e322cc90 100644 --- a/examples/talon/docker-compose.yml +++ b/examples/talon/docker-compose.yml @@ -17,6 +17,6 @@ services: command: > bash -c " mkdir -p /workspace/.deepagents/$${AGENT_ASSISTANT_ID}/agent && - cp /opt/deepagents-talon/AGENTS.md /workspace/.deepagents/$${AGENT_ASSISTANT_ID}/agent/AGENTS.md && + cp -n /opt/deepagents-talon/AGENTS.md /workspace/.deepagents/$${AGENT_ASSISTANT_ID}/agent/AGENTS.md && /opt/deepagents-talon-venv/bin/deepagents-talon " From c42e9bee32ff0775f836ab64161371bba64e09a7 Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Tue, 23 Jun 2026 21:42:40 -0700 Subject: [PATCH 44/48] feat(talon): add Telegram video media handling --- examples/talon/Dockerfile | 2 +- examples/talon/README.md | 4 +- libs/talon/deepagents_talon/channels/base.py | 5 +- .../deepagents_talon/channels/telegram.py | 31 +++++++++- libs/talon/deepagents_talon/media.py | 9 ++- libs/talon/pyproject.toml | 9 +++ libs/talon/tests/channels/test_base.py | 20 +++++- libs/talon/tests/channels/test_telegram.py | 61 +++++++++++++++++++ libs/talon/tests/test_host.py | 29 +++++++++ libs/talon/tests/test_media.py | 11 ++++ libs/talon/tests/test_speech.py | 24 ++++++++ libs/talon/uv.lock | 18 +++++- 12 files changed, 212 insertions(+), 11 deletions(-) diff --git a/examples/talon/Dockerfile b/examples/talon/Dockerfile index 3b2440bbbd2..76cf4a55c2c 100644 --- a/examples/talon/Dockerfile +++ b/examples/talon/Dockerfile @@ -56,7 +56,7 @@ RUN mkdir -p /opt/whatsapp-bridge && \ cd /opt/whatsapp-bridge && \ npm install --omit=dev -RUN cd libs/talon && uv sync --frozen --extra speech +RUN cd libs/talon && uv sync --frozen --extra media WORKDIR /workspace diff --git a/examples/talon/README.md b/examples/talon/README.md index 658b6a3734d..659b844f880 100644 --- a/examples/talon/README.md +++ b/examples/talon/README.md @@ -25,7 +25,7 @@ Uncomment the Telegram env vars in `.env` and set `DEEPAGENTS_TALON_TELEGRAM_BOT ## Voice Transcription -Voice transcription is enabled by default in `.env.example`. The Docker example installs `ffmpeg` and the Talon `speech` extra so inbound voice notes are transcribed locally with NVIDIA Parakeet through Transformers before reaching the agent. The first voice message can be slow because the ASR model is downloaded lazily. Set `DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_DEVICE=cuda` when running on a GPU-enabled host. +Voice transcription is enabled by default in `.env.example`. The Docker example installs `ffmpeg` plus the Talon `media` extra, which includes both the speech and video optional dependencies, so inbound voice notes are transcribed locally with NVIDIA Parakeet through Transformers before reaching the agent, and video files can be decoded by Deep Agents `read_file`. The first voice message can be slow because the ASR model is downloaded lazily. Set `DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_DEVICE=cuda` when running on a GPU-enabled host. Cron records, downloaded inbound media, and channel session state persist under `~/talon-workspace/.deepagents/`. The agent's default working directory is `/workspace`, so files it creates are written into `~/talon-workspace/` on the host. @@ -43,7 +43,7 @@ cd ../../libs/talon/deepagents_talon/channels/whatsapp_bridge npm install cd ../../../.. -uv sync --directory libs/talon --extra speech +uv sync --directory libs/talon --extra media cp examples/talon/AGENTS.md ~/.deepagents/talon-local/agent/AGENTS.md export DEEPAGENTS_TALON_WORKSPACE=~/talon-workspace uv run --directory libs/talon deepagents-talon --whatsapp diff --git a/libs/talon/deepagents_talon/channels/base.py b/libs/talon/deepagents_talon/channels/base.py index c523088928f..7afe4f731d1 100644 --- a/libs/talon/deepagents_talon/channels/base.py +++ b/libs/talon/deepagents_talon/channels/base.py @@ -300,7 +300,10 @@ def message_with_media_paths( metadata["media_paths"] = paths metadata["media_path"] = paths[0] metadata["media_mime_types"] = types - metadata["voice_path"] = paths[0] if metadata.get("media_type") == "voice" else None + if metadata.get("media_type") == "voice": + metadata["voice_path"] = paths[0] + else: + metadata.pop("voice_path", None) return replace(message, metadata=metadata) diff --git a/libs/talon/deepagents_talon/channels/telegram.py b/libs/talon/deepagents_talon/channels/telegram.py index ffa28c7f857..e08bbf2d45f 100644 --- a/libs/talon/deepagents_talon/channels/telegram.py +++ b/libs/talon/deepagents_talon/channels/telegram.py @@ -773,6 +773,8 @@ def _safe_suffix(file_path: str, media_type: str) -> str: return ".jpg" if media_type == "voice": return ".ogg" + if media_type == "video": + return ".mp4" return ".bin" @@ -977,6 +979,7 @@ def _extract_media_info(msg: Mapping[str, object]) -> _TelegramMediaInfo | None: """ photo = msg.get("photo") voice = msg.get("voice") or msg.get("audio") + video = msg.get("video") or msg.get("video_note") document = msg.get("document") if isinstance(photo, list) and photo: file_id = _largest_photo_file_id(photo) @@ -991,19 +994,41 @@ def _extract_media_info(msg: Mapping[str, object]) -> _TelegramMediaInfo | None: file_id=file_id, mime_type=optional_str(values.get("mime_type")), ) - if isinstance(document, dict): - values = cast("Mapping[str, object]", document) + if isinstance(video, dict): + values = cast("Mapping[str, object]", video) file_id = values.get("file_id") if isinstance(file_id, str): return _TelegramMediaInfo( - media_type="document", + media_type="video", file_id=file_id, file_name=optional_str(values.get("file_name")), mime_type=optional_str(values.get("mime_type")), ) + if isinstance(document, dict): + values = cast("Mapping[str, object]", document) + file_id = values.get("file_id") + if isinstance(file_id, str): + file_name = optional_str(values.get("file_name")) + mime_type = optional_str(values.get("mime_type")) + return _TelegramMediaInfo( + media_type=_document_media_type(file_name=file_name, mime_type=mime_type), + file_id=file_id, + file_name=file_name, + mime_type=mime_type, + ) return None +def _document_media_type(*, file_name: str | None, mime_type: str | None) -> str: + if mime_type is not None and mime_type.startswith("video/"): + return "video" + if file_name is not None: + guessed = mimetypes.guess_type(file_name)[0] + if guessed is not None and guessed.startswith("video/"): + return "video" + return "document" + + def _photo_size(size: dict[str, object]) -> int: """Extract a numeric file_size from a Telegram photo size object.""" raw = size.get("file_size") diff --git a/libs/talon/deepagents_talon/media.py b/libs/talon/deepagents_talon/media.py index 49441f4c136..a06c69a777d 100644 --- a/libs/talon/deepagents_talon/media.py +++ b/libs/talon/deepagents_talon/media.py @@ -81,11 +81,12 @@ def build_inbound_text(text: str, metadata: dict[str, object]) -> str: parts.extend(_document_parts(media_paths)) elif media_type == "image": parts.extend(_image_fallback_parts(media_paths)) + elif media_type == "video": + parts.extend(_binary_media_parts(media_paths, media_type="video")) elif media_type in {"voice", "audio"}: return text else: - names = ", ".join(path.name for path in media_paths) - parts.append(f"_(Received unsupported WhatsApp media attachment: {names}.)_") + parts.extend(_binary_media_parts(media_paths, media_type="media")) return "\n\n".join(part for part in parts if part.strip()) or text @@ -268,6 +269,10 @@ def _image_fallback_parts(paths: list[Path]) -> list[str]: return parts +def _binary_media_parts(paths: list[Path], *, media_type: str) -> list[str]: + return [f"_(Received {media_type} attachment: {path}.)_" for path in paths] + + def _media_paths(metadata: dict[str, object]) -> list[Path]: values: list[object] = [] raw_many = metadata.get("media_paths") or metadata.get("media_urls") diff --git a/libs/talon/pyproject.toml b/libs/talon/pyproject.toml index 92f6b795368..b1dbcd35dcc 100644 --- a/libs/talon/pyproject.toml +++ b/libs/talon/pyproject.toml @@ -33,6 +33,15 @@ dependencies = [ ] [project.optional-dependencies] +media = [ + "deepagents[video]>=0.6.8,<0.7.0", + "librosa>=0.11.0,<1.0.0", + "numpy>=2.4.6,<3.0.0", + "phonemizer>=3.3.0,<4.0.0", + "torch>=2.12.0,<2.13.0", + "torchaudio>=2.11.0,<2.12.0", + "transformers>=5.10.2,<6.0.0", +] speech = [ "librosa>=0.11.0,<1.0.0", "numpy>=2.4.6,<3.0.0", diff --git a/libs/talon/tests/channels/test_base.py b/libs/talon/tests/channels/test_base.py index d83c7bff6e6..e1654952b7d 100644 --- a/libs/talon/tests/channels/test_base.py +++ b/libs/talon/tests/channels/test_base.py @@ -147,6 +147,24 @@ def test_message_with_media_paths_preserves_provider_media_presence() -> None: assert with_media.metadata["has_media"] is True +def test_message_with_media_paths_adds_voice_path_only_for_voice() -> None: + voice = message_with_media_paths( + ChannelMessage(conversation_id="chat", text="", metadata={"media_type": "voice"}), + media_paths=["voice.ogg"], + ) + video = message_with_media_paths( + ChannelMessage( + conversation_id="chat", + text="", + metadata={"media_type": "video", "voice_path": None}, + ), + media_paths=["clip.mp4"], + ) + + assert voice.metadata["voice_path"] == "voice.ogg" + assert "voice_path" not in video.metadata + + def test_max_media_bytes_from_env_defaults_to_one_gb() -> None: assert max_media_bytes_from_env({}) == DEFAULT_MAX_MEDIA_BYTES @@ -172,7 +190,7 @@ async def legacy_send() -> None: async def test_send_with_retry_treats_none_return_as_success_on_retry() -> None: calls = 0 - async def flaky_legacy_send() -> None: + async def flaky_legacy_send() -> SendResult | None: nonlocal calls calls += 1 if calls == 1: diff --git a/libs/talon/tests/channels/test_telegram.py b/libs/talon/tests/channels/test_telegram.py index be9e73a46c0..fe7817161f5 100644 --- a/libs/talon/tests/channels/test_telegram.py +++ b/libs/talon/tests/channels/test_telegram.py @@ -73,6 +73,10 @@ async def call(self, method: str, **params: object) -> object: file_id = params.get("file_id") if file_id == "voice123": file_path = "voice/file.oga" + elif file_id in {"video123", "note123"}: + file_path = "videos/file.mp4" + elif file_id == "docvideo123": + file_path = "documents/clip.mp4" elif file_id == "doc123": file_path = "documents/report.pdf" else: @@ -120,6 +124,8 @@ def _make_update( # noqa: PLR0913 # test helper with many optional fields message_id: int = 10, photo: list | None = None, voice: dict | None = None, + video: dict | None = None, + video_note: dict | None = None, document: dict | None = None, ) -> dict[str, object]: message: dict[str, object] = { @@ -132,6 +138,10 @@ def _make_update( # noqa: PLR0913 # test helper with many optional fields message["photo"] = photo if voice is not None: message["voice"] = voice + if video is not None: + message["video"] = video + if video_note is not None: + message["video_note"] = video_note if document is not None: message["document"] = document return {"update_id": update_id, "message": message} @@ -869,6 +879,55 @@ async def test_channel_parses_inbound_media( "suffix": ".pdf", }, ), + ( + "video", + _make_update( + chat_id=111, + sender_id=111, + text="", + video={ + "file_id": "video123", + "file_name": "clip.mp4", + "mime_type": "video/mp4", + }, + ), + { + "media_type": "video", + "file_id": "video123", + "media_mime_types": ["video/mp4"], + "suffix": ".mp4", + }, + ), + ( + "video_note", + _make_update( + chat_id=111, + sender_id=111, + text="", + video_note={"file_id": "note123", "duration": 8, "length": 240}, + ), + {"media_type": "video", "file_id": "note123", "suffix": ".mp4"}, + ), + ( + "document_video", + _make_update( + chat_id=111, + sender_id=111, + text="", + document={ + "file_id": "docvideo123", + "file_name": "clip.mp4", + "mime_type": "video/mp4", + }, + ), + { + "media_type": "video", + "file_id": "docvideo123", + "file_name": "clip.mp4", + "media_mime_types": ["video/mp4"], + "suffix": ".mp4", + }, + ), ) for name, update, expected in cases: @@ -894,6 +953,8 @@ async def test_channel_parses_inbound_media( assert metadata["media_mime_types"] == expected["media_mime_types"] if expected.get("voice_path") is True: assert metadata["voice_path"] == expected_path + else: + assert "voice_path" not in metadata media_path = Path(cast("str", metadata["media_path"])) assert await asyncio.to_thread(media_path.read_bytes) == b"media-bytes" diff --git a/libs/talon/tests/test_host.py b/libs/talon/tests/test_host.py index 1d147f10ff1..0d1af771cdd 100644 --- a/libs/talon/tests/test_host.py +++ b/libs/talon/tests/test_host.py @@ -310,6 +310,35 @@ async def test_host_passes_inbound_photo_as_model_content(tmp_path: Path) -> Non assert content[1]["type"] == "image_url" +async def test_host_passes_inbound_video_path_in_text(tmp_path: Path) -> None: + channel = RecordingChannel() + video = tmp_path / "inbound.mp4" + video.write_bytes(b"video-bytes") + agent = BlockingAgent() + host = TalonHost(config=_config(tmp_path), agent=agent, channels=[channel]) + await host.start() + + await host.receive_message( + channel, + ChannelMessage( + conversation_id="chat", + text="watch this", + metadata={ + "media_type": "video", + "media_paths": [str(video)], + "media_mime_types": ["video/mp4"], + }, + ), + ) + await _wait_for_request(agent, f"watch this\n\n_(Received video attachment: {video}.)_") + await host.stop() + + request = agent.requests[0] + assert "unsupported" not in request.text + assert request.metadata["media_type"] == "video" + assert request.metadata["media_paths"] == [str(video)] + + async def test_host_routes_tool_approval_reply_to_pending_run(tmp_path: Path) -> None: channel = RecordingChannel() agent = ApprovalAgent() diff --git a/libs/talon/tests/test_media.py b/libs/talon/tests/test_media.py index 38e8880baa2..74d900ca27e 100644 --- a/libs/talon/tests/test_media.py +++ b/libs/talon/tests/test_media.py @@ -41,6 +41,17 @@ def test_build_inbound_text_bounds_document_extraction(tmp_path: Path) -> None: assert "large.txt" in text +def test_build_inbound_text_includes_video_path(tmp_path: Path) -> None: + video = tmp_path / "clip.mp4" + video.write_bytes(b"video") + + text = build_inbound_text("watch this", {"media_type": "video", "media_paths": [str(video)]}) + + assert "watch this" in text + assert f"Received video attachment: {video}" in text + assert "unsupported" not in text + + def test_build_model_content_uses_inbound_image_data_url(tmp_path: Path) -> None: image = tmp_path / "image.png" image.write_bytes(b"not-a-real-png") diff --git a/libs/talon/tests/test_speech.py b/libs/talon/tests/test_speech.py index 8a66133b4af..e1795943ce8 100644 --- a/libs/talon/tests/test_speech.py +++ b/libs/talon/tests/test_speech.py @@ -1,11 +1,13 @@ from pathlib import Path from deepagents_talon.config import TalonConfig +from deepagents_talon.interfaces import ChannelMessage from deepagents_talon.speech import ( DEFAULT_LOCAL_VOICE_TRANSCRIPTION_MODEL, LocalParakeetVoiceTranscriber, OpenAIVoiceTranscriber, build_voice_transcriber, + transcribe_voice_message, ) @@ -63,3 +65,25 @@ def test_build_voice_transcriber_preserves_openai_model_override(tmp_path: Path) assert isinstance(transcriber, OpenAIVoiceTranscriber) assert transcriber.model == "gpt-4o-transcribe" + + +async def test_transcribe_voice_message_ignores_video_media_path() -> None: + class Transcriber: + def __init__(self) -> None: + self.calls = 0 + + async def transcribe(self, message: ChannelMessage) -> str | None: # noqa: ARG002 + self.calls += 1 + return "transcribed" + + transcriber = Transcriber() + message = ChannelMessage( + conversation_id="chat", + text="video", + metadata={"media_type": "video", "media_path": "clip.mp4"}, + ) + + updated = await transcribe_voice_message(transcriber, message) + + assert updated == message + assert transcriber.calls == 0 diff --git a/libs/talon/uv.lock b/libs/talon/uv.lock index df483742ceb..a1d6db2a3f5 100644 --- a/libs/talon/uv.lock +++ b/libs/talon/uv.lock @@ -858,6 +858,15 @@ dependencies = [ ] [package.optional-dependencies] +media = [ + { name = "deepagents", extra = ["video"] }, + { name = "librosa" }, + { name = "numpy" }, + { name = "phonemizer" }, + { name = "torch" }, + { name = "torchaudio" }, + { name = "transformers" }, +] speech = [ { name = "librosa" }, { name = "numpy" }, @@ -882,17 +891,24 @@ test = [ [package.metadata] requires-dist = [ { name = "deepagents", editable = "../deepagents" }, + { name = "deepagents", extras = ["video"], marker = "extra == 'media'", editable = "../deepagents" }, { name = "deepagents-code", editable = "../code" }, { name = "fleet-deepagents-export", specifier = ">=0.0.1,<1.0.0" }, { name = "langchain-mcp-adapters", specifier = ">=0.2.2,<1.0.0" }, + { name = "librosa", marker = "extra == 'media'", specifier = ">=0.11.0,<1.0.0" }, { name = "librosa", marker = "extra == 'speech'", specifier = ">=0.11.0,<1.0.0" }, + { name = "numpy", marker = "extra == 'media'", specifier = ">=2.4.6,<3.0.0" }, { name = "numpy", marker = "extra == 'speech'", specifier = ">=2.4.6,<3.0.0" }, + { name = "phonemizer", marker = "extra == 'media'", specifier = ">=3.3.0,<4.0.0" }, { name = "phonemizer", marker = "extra == 'speech'", specifier = ">=3.3.0,<4.0.0" }, + { name = "torch", marker = "extra == 'media'", specifier = ">=2.12.0,<2.13.0" }, { name = "torch", marker = "extra == 'speech'", specifier = ">=2.12.0,<2.13.0" }, + { name = "torchaudio", marker = "extra == 'media'", specifier = ">=2.11.0,<2.12.0" }, { name = "torchaudio", marker = "extra == 'speech'", specifier = ">=2.11.0,<2.12.0" }, + { name = "transformers", marker = "extra == 'media'", specifier = ">=5.10.2,<6.0.0" }, { name = "transformers", marker = "extra == 'speech'", specifier = ">=5.10.2,<6.0.0" }, ] -provides-extras = ["speech"] +provides-extras = ["media", "speech"] [package.metadata.requires-dev] test = [ From a23679c2606c40ae2928093d80a10682dc6aa680 Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Tue, 23 Jun 2026 22:00:45 -0700 Subject: [PATCH 45/48] chore(talon): consolidate optional media extra --- examples/talon/README.md | 2 +- libs/talon/pyproject.toml | 10 ---------- libs/talon/uv.lock | 18 +----------------- 3 files changed, 2 insertions(+), 28 deletions(-) diff --git a/examples/talon/README.md b/examples/talon/README.md index 659b844f880..7e3a69aac7a 100644 --- a/examples/talon/README.md +++ b/examples/talon/README.md @@ -25,7 +25,7 @@ Uncomment the Telegram env vars in `.env` and set `DEEPAGENTS_TALON_TELEGRAM_BOT ## Voice Transcription -Voice transcription is enabled by default in `.env.example`. The Docker example installs `ffmpeg` plus the Talon `media` extra, which includes both the speech and video optional dependencies, so inbound voice notes are transcribed locally with NVIDIA Parakeet through Transformers before reaching the agent, and video files can be decoded by Deep Agents `read_file`. The first voice message can be slow because the ASR model is downloaded lazily. Set `DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_DEVICE=cuda` when running on a GPU-enabled host. +Voice transcription is enabled by default in `.env.example`. The Docker example installs `ffmpeg` plus the Talon `media` extra, so inbound voice notes are transcribed locally with NVIDIA Parakeet through Transformers before reaching the agent, and video files can be decoded by Deep Agents `read_file`. The first voice message can be slow because the ASR model is downloaded lazily. Set `DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_DEVICE=cuda` when running on a GPU-enabled host. Cron records, downloaded inbound media, and channel session state persist under `~/talon-workspace/.deepagents/`. The agent's default working directory is `/workspace`, so files it creates are written into `~/talon-workspace/` on the host. diff --git a/libs/talon/pyproject.toml b/libs/talon/pyproject.toml index b1dbcd35dcc..2272637d853 100644 --- a/libs/talon/pyproject.toml +++ b/libs/talon/pyproject.toml @@ -34,7 +34,6 @@ dependencies = [ [project.optional-dependencies] media = [ - "deepagents[video]>=0.6.8,<0.7.0", "librosa>=0.11.0,<1.0.0", "numpy>=2.4.6,<3.0.0", "phonemizer>=3.3.0,<4.0.0", @@ -42,15 +41,6 @@ media = [ "torchaudio>=2.11.0,<2.12.0", "transformers>=5.10.2,<6.0.0", ] -speech = [ - "librosa>=0.11.0,<1.0.0", - "numpy>=2.4.6,<3.0.0", - "phonemizer>=3.3.0,<4.0.0", - "torch>=2.12.0,<2.13.0", - "torchaudio>=2.11.0,<2.12.0", - "transformers>=5.10.2,<6.0.0", -] - [project.scripts] deepagents-talon = "deepagents_talon.__main__:main" diff --git a/libs/talon/uv.lock b/libs/talon/uv.lock index a1d6db2a3f5..a76902b579c 100644 --- a/libs/talon/uv.lock +++ b/libs/talon/uv.lock @@ -859,15 +859,6 @@ dependencies = [ [package.optional-dependencies] media = [ - { name = "deepagents", extra = ["video"] }, - { name = "librosa" }, - { name = "numpy" }, - { name = "phonemizer" }, - { name = "torch" }, - { name = "torchaudio" }, - { name = "transformers" }, -] -speech = [ { name = "librosa" }, { name = "numpy" }, { name = "phonemizer" }, @@ -891,24 +882,17 @@ test = [ [package.metadata] requires-dist = [ { name = "deepagents", editable = "../deepagents" }, - { name = "deepagents", extras = ["video"], marker = "extra == 'media'", editable = "../deepagents" }, { name = "deepagents-code", editable = "../code" }, { name = "fleet-deepagents-export", specifier = ">=0.0.1,<1.0.0" }, { name = "langchain-mcp-adapters", specifier = ">=0.2.2,<1.0.0" }, { name = "librosa", marker = "extra == 'media'", specifier = ">=0.11.0,<1.0.0" }, - { name = "librosa", marker = "extra == 'speech'", specifier = ">=0.11.0,<1.0.0" }, { name = "numpy", marker = "extra == 'media'", specifier = ">=2.4.6,<3.0.0" }, - { name = "numpy", marker = "extra == 'speech'", specifier = ">=2.4.6,<3.0.0" }, { name = "phonemizer", marker = "extra == 'media'", specifier = ">=3.3.0,<4.0.0" }, - { name = "phonemizer", marker = "extra == 'speech'", specifier = ">=3.3.0,<4.0.0" }, { name = "torch", marker = "extra == 'media'", specifier = ">=2.12.0,<2.13.0" }, - { name = "torch", marker = "extra == 'speech'", specifier = ">=2.12.0,<2.13.0" }, { name = "torchaudio", marker = "extra == 'media'", specifier = ">=2.11.0,<2.12.0" }, - { name = "torchaudio", marker = "extra == 'speech'", specifier = ">=2.11.0,<2.12.0" }, { name = "transformers", marker = "extra == 'media'", specifier = ">=5.10.2,<6.0.0" }, - { name = "transformers", marker = "extra == 'speech'", specifier = ">=5.10.2,<6.0.0" }, ] -provides-extras = ["media", "speech"] +provides-extras = ["media"] [package.metadata.requires-dev] test = [ From 5d6e30f627fb92acfd6dbddd5c78e33200dd92c2 Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Tue, 23 Jun 2026 22:14:52 -0700 Subject: [PATCH 46/48] chore(talon): revert optional media extra --- examples/talon/Dockerfile | 2 +- examples/talon/README.md | 4 ++-- libs/talon/pyproject.toml | 3 ++- libs/talon/uv.lock | 18 +++++++++--------- 4 files changed, 14 insertions(+), 13 deletions(-) diff --git a/examples/talon/Dockerfile b/examples/talon/Dockerfile index 76cf4a55c2c..3b2440bbbd2 100644 --- a/examples/talon/Dockerfile +++ b/examples/talon/Dockerfile @@ -56,7 +56,7 @@ RUN mkdir -p /opt/whatsapp-bridge && \ cd /opt/whatsapp-bridge && \ npm install --omit=dev -RUN cd libs/talon && uv sync --frozen --extra media +RUN cd libs/talon && uv sync --frozen --extra speech WORKDIR /workspace diff --git a/examples/talon/README.md b/examples/talon/README.md index 7e3a69aac7a..793677b21ac 100644 --- a/examples/talon/README.md +++ b/examples/talon/README.md @@ -25,7 +25,7 @@ Uncomment the Telegram env vars in `.env` and set `DEEPAGENTS_TALON_TELEGRAM_BOT ## Voice Transcription -Voice transcription is enabled by default in `.env.example`. The Docker example installs `ffmpeg` plus the Talon `media` extra, so inbound voice notes are transcribed locally with NVIDIA Parakeet through Transformers before reaching the agent, and video files can be decoded by Deep Agents `read_file`. The first voice message can be slow because the ASR model is downloaded lazily. Set `DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_DEVICE=cuda` when running on a GPU-enabled host. +Voice transcription is enabled by default in `.env.example`. The Docker example installs `ffmpeg` plus the Talon `speech` extra, so inbound voice notes are transcribed locally with NVIDIA Parakeet through Transformers before reaching the agent. The first voice message can be slow because the ASR model is downloaded lazily. Set `DEEPAGENTS_TALON_VOICE_TRANSCRIPTION_DEVICE=cuda` when running on a GPU-enabled host. Cron records, downloaded inbound media, and channel session state persist under `~/talon-workspace/.deepagents/`. The agent's default working directory is `/workspace`, so files it creates are written into `~/talon-workspace/` on the host. @@ -43,7 +43,7 @@ cd ../../libs/talon/deepagents_talon/channels/whatsapp_bridge npm install cd ../../../.. -uv sync --directory libs/talon --extra media +uv sync --directory libs/talon --extra speech cp examples/talon/AGENTS.md ~/.deepagents/talon-local/agent/AGENTS.md export DEEPAGENTS_TALON_WORKSPACE=~/talon-workspace uv run --directory libs/talon deepagents-talon --whatsapp diff --git a/libs/talon/pyproject.toml b/libs/talon/pyproject.toml index 2272637d853..92f6b795368 100644 --- a/libs/talon/pyproject.toml +++ b/libs/talon/pyproject.toml @@ -33,7 +33,7 @@ dependencies = [ ] [project.optional-dependencies] -media = [ +speech = [ "librosa>=0.11.0,<1.0.0", "numpy>=2.4.6,<3.0.0", "phonemizer>=3.3.0,<4.0.0", @@ -41,6 +41,7 @@ media = [ "torchaudio>=2.11.0,<2.12.0", "transformers>=5.10.2,<6.0.0", ] + [project.scripts] deepagents-talon = "deepagents_talon.__main__:main" diff --git a/libs/talon/uv.lock b/libs/talon/uv.lock index a76902b579c..df483742ceb 100644 --- a/libs/talon/uv.lock +++ b/libs/talon/uv.lock @@ -858,7 +858,7 @@ dependencies = [ ] [package.optional-dependencies] -media = [ +speech = [ { name = "librosa" }, { name = "numpy" }, { name = "phonemizer" }, @@ -885,14 +885,14 @@ requires-dist = [ { name = "deepagents-code", editable = "../code" }, { name = "fleet-deepagents-export", specifier = ">=0.0.1,<1.0.0" }, { name = "langchain-mcp-adapters", specifier = ">=0.2.2,<1.0.0" }, - { name = "librosa", marker = "extra == 'media'", specifier = ">=0.11.0,<1.0.0" }, - { name = "numpy", marker = "extra == 'media'", specifier = ">=2.4.6,<3.0.0" }, - { name = "phonemizer", marker = "extra == 'media'", specifier = ">=3.3.0,<4.0.0" }, - { name = "torch", marker = "extra == 'media'", specifier = ">=2.12.0,<2.13.0" }, - { name = "torchaudio", marker = "extra == 'media'", specifier = ">=2.11.0,<2.12.0" }, - { name = "transformers", marker = "extra == 'media'", specifier = ">=5.10.2,<6.0.0" }, -] -provides-extras = ["media"] + { name = "librosa", marker = "extra == 'speech'", specifier = ">=0.11.0,<1.0.0" }, + { name = "numpy", marker = "extra == 'speech'", specifier = ">=2.4.6,<3.0.0" }, + { name = "phonemizer", marker = "extra == 'speech'", specifier = ">=3.3.0,<4.0.0" }, + { name = "torch", marker = "extra == 'speech'", specifier = ">=2.12.0,<2.13.0" }, + { name = "torchaudio", marker = "extra == 'speech'", specifier = ">=2.11.0,<2.12.0" }, + { name = "transformers", marker = "extra == 'speech'", specifier = ">=5.10.2,<6.0.0" }, +] +provides-extras = ["speech"] [package.metadata.requires-dev] test = [ From f104843076cc9669e3e178b440a97b858cb6743e Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Wed, 24 Jun 2026 00:24:04 -0700 Subject: [PATCH 47/48] feat(talon): transcribe audio from video and audio document media Broaden ASR eligibility so that video files and audio-typed documents sent via Telegram or WhatsApp are transcribed when voice packages are installed and enabled. Previously only `voice` media type triggered transcription. - `_is_voice_message` now matches `media_type == "video"` and checks `media_mime_types` for `audio/*` MIME types - `_document_media_type` classifies documents with audio MIME types or audio file extensions as `voice` instead of `document` - `message_with_media_paths` sets `voice_path` for `video` media so the transcriber can locate the file - ffmpeg's `_convert_to_wav` already extracts audio from video containers, so no change needed there --- libs/talon/deepagents_talon/channels/base.py | 2 +- .../deepagents_talon/channels/telegram.py | 4 ++ libs/talon/deepagents_talon/speech.py | 16 ++++++- libs/talon/tests/channels/test_base.py | 4 +- libs/talon/tests/channels/test_telegram.py | 29 +++++++++++- libs/talon/tests/test_speech.py | 47 ++++++++++++++++++- 6 files changed, 95 insertions(+), 7 deletions(-) diff --git a/libs/talon/deepagents_talon/channels/base.py b/libs/talon/deepagents_talon/channels/base.py index 7afe4f731d1..bb63eec11e1 100644 --- a/libs/talon/deepagents_talon/channels/base.py +++ b/libs/talon/deepagents_talon/channels/base.py @@ -300,7 +300,7 @@ def message_with_media_paths( metadata["media_paths"] = paths metadata["media_path"] = paths[0] metadata["media_mime_types"] = types - if metadata.get("media_type") == "voice": + if metadata.get("media_type") in {"voice", "video"}: metadata["voice_path"] = paths[0] else: metadata.pop("voice_path", None) diff --git a/libs/talon/deepagents_talon/channels/telegram.py b/libs/talon/deepagents_talon/channels/telegram.py index e08bbf2d45f..8646f71984f 100644 --- a/libs/talon/deepagents_talon/channels/telegram.py +++ b/libs/talon/deepagents_talon/channels/telegram.py @@ -1020,10 +1020,14 @@ def _extract_media_info(msg: Mapping[str, object]) -> _TelegramMediaInfo | None: def _document_media_type(*, file_name: str | None, mime_type: str | None) -> str: + if mime_type is not None and mime_type.startswith("audio/"): + return "voice" if mime_type is not None and mime_type.startswith("video/"): return "video" if file_name is not None: guessed = mimetypes.guess_type(file_name)[0] + if guessed is not None and guessed.startswith("audio/"): + return "voice" if guessed is not None and guessed.startswith("video/"): return "video" return "document" diff --git a/libs/talon/deepagents_talon/speech.py b/libs/talon/deepagents_talon/speech.py index 906fa58c5b1..d0f9dca16a0 100644 --- a/libs/talon/deepagents_talon/speech.py +++ b/libs/talon/deepagents_talon/speech.py @@ -185,8 +185,22 @@ async def transcribe_voice_message( ) +_ASR_ELIGIBLE_MEDIA_TYPES = frozenset({"voice", "video"}) + + def _is_voice_message(message: ChannelMessage) -> bool: - return message.metadata.get("media_type") == "voice" or "voice_path" in message.metadata + if "voice_path" in message.metadata: + return True + media_type = message.metadata.get("media_type") + if isinstance(media_type, str) and media_type in _ASR_ELIGIBLE_MEDIA_TYPES: + return True + for key in ("media_mime_types", "media_mime_type"): + raw = message.metadata.get(key) + if isinstance(raw, list): + return any(isinstance(m, str) and m.startswith("audio/") for m in raw) + if isinstance(raw, str) and raw.startswith("audio/"): + return True + return False def _voice_path(message: ChannelMessage) -> Path | None: diff --git a/libs/talon/tests/channels/test_base.py b/libs/talon/tests/channels/test_base.py index e1654952b7d..dd9328d58ee 100644 --- a/libs/talon/tests/channels/test_base.py +++ b/libs/talon/tests/channels/test_base.py @@ -147,7 +147,7 @@ def test_message_with_media_paths_preserves_provider_media_presence() -> None: assert with_media.metadata["has_media"] is True -def test_message_with_media_paths_adds_voice_path_only_for_voice() -> None: +def test_message_with_media_paths_adds_voice_path_for_voice_and_video() -> None: voice = message_with_media_paths( ChannelMessage(conversation_id="chat", text="", metadata={"media_type": "voice"}), media_paths=["voice.ogg"], @@ -162,7 +162,7 @@ def test_message_with_media_paths_adds_voice_path_only_for_voice() -> None: ) assert voice.metadata["voice_path"] == "voice.ogg" - assert "voice_path" not in video.metadata + assert video.metadata["voice_path"] == "clip.mp4" def test_max_media_bytes_from_env_defaults_to_one_gb() -> None: diff --git a/libs/talon/tests/channels/test_telegram.py b/libs/talon/tests/channels/test_telegram.py index fe7817161f5..1206a836656 100644 --- a/libs/talon/tests/channels/test_telegram.py +++ b/libs/talon/tests/channels/test_telegram.py @@ -56,7 +56,7 @@ def __init__( self.uploads: list[tuple[str, str, Path, dict[str, object]]] = [] self._get_me_called = False - async def call(self, method: str, **params: object) -> object: + async def call(self, method: str, **params: object) -> object: # noqa: C901 # test mock dispatch self.calls.append((method, dict(params))) if method == "getMe": self._get_me_called = True @@ -79,6 +79,8 @@ async def call(self, method: str, **params: object) -> object: file_path = "documents/clip.mp4" elif file_id == "doc123": file_path = "documents/report.pdf" + elif file_id == "docaudio123": + file_path = "music/file.mp3" else: file_path = "photos/file.jpg" return {"file_id": file_id, "file_path": file_path} @@ -896,6 +898,7 @@ async def test_channel_parses_inbound_media( "file_id": "video123", "media_mime_types": ["video/mp4"], "suffix": ".mp4", + "voice_path": True, }, ), ( @@ -906,7 +909,7 @@ async def test_channel_parses_inbound_media( text="", video_note={"file_id": "note123", "duration": 8, "length": 240}, ), - {"media_type": "video", "file_id": "note123", "suffix": ".mp4"}, + {"media_type": "video", "file_id": "note123", "suffix": ".mp4", "voice_path": True}, ), ( "document_video", @@ -926,6 +929,28 @@ async def test_channel_parses_inbound_media( "file_name": "clip.mp4", "media_mime_types": ["video/mp4"], "suffix": ".mp4", + "voice_path": True, + }, + ), + ( + "document_audio", + _make_update( + chat_id=111, + sender_id=111, + text="", + document={ + "file_id": "docaudio123", + "file_name": "song.mp3", + "mime_type": "audio/mpeg", + }, + ), + { + "media_type": "voice", + "file_id": "docaudio123", + "file_name": "song.mp3", + "media_mime_types": ["audio/mpeg"], + "suffix": ".mp3", + "voice_path": True, }, ), ) diff --git a/libs/talon/tests/test_speech.py b/libs/talon/tests/test_speech.py index e1795943ce8..8dd19b6d4cc 100644 --- a/libs/talon/tests/test_speech.py +++ b/libs/talon/tests/test_speech.py @@ -67,7 +67,7 @@ def test_build_voice_transcriber_preserves_openai_model_override(tmp_path: Path) assert transcriber.model == "gpt-4o-transcribe" -async def test_transcribe_voice_message_ignores_video_media_path() -> None: +async def test_transcribe_voice_message_transcribes_video() -> None: class Transcriber: def __init__(self) -> None: self.calls = 0 @@ -85,5 +85,50 @@ async def transcribe(self, message: ChannelMessage) -> str | None: # noqa: ARG0 updated = await transcribe_voice_message(transcriber, message) + assert transcriber.calls == 1 + assert "transcribed" in updated.text + + +async def test_transcribe_voice_message_transcribes_audio_mime_document() -> None: + class Transcriber: + def __init__(self) -> None: + self.calls = 0 + + async def transcribe(self, message: ChannelMessage) -> str | None: # noqa: ARG002 + self.calls += 1 + return "transcribed" + + transcriber = Transcriber() + message = ChannelMessage( + conversation_id="chat", + text="", + metadata={"media_type": "document", "media_path": "song.mp3", + "media_mime_types": ["audio/mpeg"]}, + ) + + updated = await transcribe_voice_message(transcriber, message) + + assert transcriber.calls == 1 + assert "transcribed" in updated.text + + +async def test_transcribe_voice_message_ignores_plain_document() -> None: + class Transcriber: + def __init__(self) -> None: + self.calls = 0 + + async def transcribe(self, message: ChannelMessage) -> str | None: # noqa: ARG002 + self.calls += 1 + return "transcribed" + + transcriber = Transcriber() + message = ChannelMessage( + conversation_id="chat", + text="doc", + metadata={"media_type": "document", "media_path": "report.pdf"}, + ) + + updated = await transcribe_voice_message(transcriber, message) + assert updated == message assert transcriber.calls == 0 From 68961c5bb6374c94c0a49eb1432aeed1ee8834ae Mon Sep 17 00:00:00 2001 From: Deep Agent Date: Wed, 24 Jun 2026 00:39:16 -0700 Subject: [PATCH 48/48] refactor(talon): simplify audio/video media settings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Move `_ASR_ELIGIBLE_MEDIA_TYPES` constant from `speech.py` to `base.py` as `ASR_ELIGIBLE_MEDIA_TYPES` and import it in `speech.py`, eliminating the duplicated `{"voice", "video"}` set - Collapse `_document_media_type` from 4 sequential if-blocks to a 2-iteration loop over `(mime_type, guessed)` - Stop setting `voice_path` for video in `message_with_media_paths` — video transcription still works via `ASR_ELIGIBLE_MEDIA_TYPES` check in `_is_voice_message` and `media_path` fallback in `_voice_path` - Remove the dead MIME-type scan branch from `_is_voice_message` — `_document_media_type` now classifies audio documents as `"voice"` upstream, making the scan unreachable in the real channel pipeline --- libs/talon/deepagents_talon/channels/base.py | 5 ++++- .../talon/deepagents_talon/channels/telegram.py | 17 +++++++---------- libs/talon/deepagents_talon/speech.py | 14 ++------------ libs/talon/tests/channels/test_base.py | 4 ++-- libs/talon/tests/channels/test_telegram.py | 4 +--- libs/talon/tests/test_speech.py | 9 ++++++--- 6 files changed, 22 insertions(+), 31 deletions(-) diff --git a/libs/talon/deepagents_talon/channels/base.py b/libs/talon/deepagents_talon/channels/base.py index bb63eec11e1..4940a648ad4 100644 --- a/libs/talon/deepagents_talon/channels/base.py +++ b/libs/talon/deepagents_talon/channels/base.py @@ -30,6 +30,9 @@ OUTBOUND_MEDIA_DIR_ENV = "DEEPAGENTS_TALON_OUTBOUND_MEDIA_DIR" WORKSPACE_ENV = "DEEPAGENTS_TALON_WORKSPACE" +ASR_ELIGIBLE_MEDIA_TYPES = frozenset({"voice", "video"}) +"""Media types that may contain audio eligible for ASR transcription.""" + _LINK_PATTERN = re.compile(r"\[([^\]]+)]\(([^)]+)\)") _HEADING_PATTERN = re.compile(r"^#{1,6}\s+", flags=re.MULTILINE) _BOLD_PATTERN = re.compile(r"\*\*([^*]+)\*\*|__([^_]+)__") @@ -300,7 +303,7 @@ def message_with_media_paths( metadata["media_paths"] = paths metadata["media_path"] = paths[0] metadata["media_mime_types"] = types - if metadata.get("media_type") in {"voice", "video"}: + if metadata.get("media_type") == "voice": metadata["voice_path"] = paths[0] else: metadata.pop("voice_path", None) diff --git a/libs/talon/deepagents_talon/channels/telegram.py b/libs/talon/deepagents_talon/channels/telegram.py index 8646f71984f..29eb8cee508 100644 --- a/libs/talon/deepagents_talon/channels/telegram.py +++ b/libs/talon/deepagents_talon/channels/telegram.py @@ -1020,16 +1020,13 @@ def _extract_media_info(msg: Mapping[str, object]) -> _TelegramMediaInfo | None: def _document_media_type(*, file_name: str | None, mime_type: str | None) -> str: - if mime_type is not None and mime_type.startswith("audio/"): - return "voice" - if mime_type is not None and mime_type.startswith("video/"): - return "video" - if file_name is not None: - guessed = mimetypes.guess_type(file_name)[0] - if guessed is not None and guessed.startswith("audio/"): - return "voice" - if guessed is not None and guessed.startswith("video/"): - return "video" + guessed = mimetypes.guess_type(file_name)[0] if file_name else None + for candidate in (mime_type, guessed): + if candidate is not None: + if candidate.startswith("audio/"): + return "voice" + if candidate.startswith("video/"): + return "video" return "document" diff --git a/libs/talon/deepagents_talon/speech.py b/libs/talon/deepagents_talon/speech.py index d0f9dca16a0..5ba25d5297b 100644 --- a/libs/talon/deepagents_talon/speech.py +++ b/libs/talon/deepagents_talon/speech.py @@ -16,6 +16,7 @@ from pathlib import Path from typing import TYPE_CHECKING, Protocol, cast +from deepagents_talon.channels.base import ASR_ELIGIBLE_MEDIA_TYPES from deepagents_talon.interfaces import ChannelMessage if TYPE_CHECKING: @@ -185,22 +186,11 @@ async def transcribe_voice_message( ) -_ASR_ELIGIBLE_MEDIA_TYPES = frozenset({"voice", "video"}) - - def _is_voice_message(message: ChannelMessage) -> bool: if "voice_path" in message.metadata: return True media_type = message.metadata.get("media_type") - if isinstance(media_type, str) and media_type in _ASR_ELIGIBLE_MEDIA_TYPES: - return True - for key in ("media_mime_types", "media_mime_type"): - raw = message.metadata.get(key) - if isinstance(raw, list): - return any(isinstance(m, str) and m.startswith("audio/") for m in raw) - if isinstance(raw, str) and raw.startswith("audio/"): - return True - return False + return isinstance(media_type, str) and media_type in ASR_ELIGIBLE_MEDIA_TYPES def _voice_path(message: ChannelMessage) -> Path | None: diff --git a/libs/talon/tests/channels/test_base.py b/libs/talon/tests/channels/test_base.py index dd9328d58ee..e1654952b7d 100644 --- a/libs/talon/tests/channels/test_base.py +++ b/libs/talon/tests/channels/test_base.py @@ -147,7 +147,7 @@ def test_message_with_media_paths_preserves_provider_media_presence() -> None: assert with_media.metadata["has_media"] is True -def test_message_with_media_paths_adds_voice_path_for_voice_and_video() -> None: +def test_message_with_media_paths_adds_voice_path_only_for_voice() -> None: voice = message_with_media_paths( ChannelMessage(conversation_id="chat", text="", metadata={"media_type": "voice"}), media_paths=["voice.ogg"], @@ -162,7 +162,7 @@ def test_message_with_media_paths_adds_voice_path_for_voice_and_video() -> None: ) assert voice.metadata["voice_path"] == "voice.ogg" - assert video.metadata["voice_path"] == "clip.mp4" + assert "voice_path" not in video.metadata def test_max_media_bytes_from_env_defaults_to_one_gb() -> None: diff --git a/libs/talon/tests/channels/test_telegram.py b/libs/talon/tests/channels/test_telegram.py index 1206a836656..5e3ecaec13a 100644 --- a/libs/talon/tests/channels/test_telegram.py +++ b/libs/talon/tests/channels/test_telegram.py @@ -898,7 +898,6 @@ async def test_channel_parses_inbound_media( "file_id": "video123", "media_mime_types": ["video/mp4"], "suffix": ".mp4", - "voice_path": True, }, ), ( @@ -909,7 +908,7 @@ async def test_channel_parses_inbound_media( text="", video_note={"file_id": "note123", "duration": 8, "length": 240}, ), - {"media_type": "video", "file_id": "note123", "suffix": ".mp4", "voice_path": True}, + {"media_type": "video", "file_id": "note123", "suffix": ".mp4"}, ), ( "document_video", @@ -929,7 +928,6 @@ async def test_channel_parses_inbound_media( "file_name": "clip.mp4", "media_mime_types": ["video/mp4"], "suffix": ".mp4", - "voice_path": True, }, ), ( diff --git a/libs/talon/tests/test_speech.py b/libs/talon/tests/test_speech.py index 8dd19b6d4cc..57473dbb281 100644 --- a/libs/talon/tests/test_speech.py +++ b/libs/talon/tests/test_speech.py @@ -89,7 +89,7 @@ async def transcribe(self, message: ChannelMessage) -> str | None: # noqa: ARG0 assert "transcribed" in updated.text -async def test_transcribe_voice_message_transcribes_audio_mime_document() -> None: +async def test_transcribe_voice_message_transcribes_audio_document() -> None: class Transcriber: def __init__(self) -> None: self.calls = 0 @@ -102,8 +102,11 @@ async def transcribe(self, message: ChannelMessage) -> str | None: # noqa: ARG0 message = ChannelMessage( conversation_id="chat", text="", - metadata={"media_type": "document", "media_path": "song.mp3", - "media_mime_types": ["audio/mpeg"]}, + metadata={ + "media_type": "voice", + "media_path": "song.mp3", + "media_mime_types": ["audio/mpeg"], + }, ) updated = await transcribe_voice_message(transcriber, message)