Skip to content

The agent that grows with you

fix(telegram): match CRLF-terminated closing fences

PRATHAMESH753480de040276
diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.py
index 9469223299a..3ca7ed643bd 100644
--- a/plugins/platforms/telegram/adapter.py
+++ b/plugins/platforms/telegram/adapter.py
@@ -5727,6 +5727,9 @@ class TelegramAdapter(BasePlatformAdapter):
# indent allowed). Anchoring to line starts keeps *inline* triple
# backticks (e.g. "the syntax is ```x``` inline") from being
# swallowed and mangled into broken MarkdownV2 <pre> entities.
+ # The trailing ``\r?`` on the close lets CRLF-terminated fences
+ # (Windows-authored content) match too, so they aren't left
+ # unprotected with their backticks escaped into literals.
def _protect_fenced(m):
opening = m.group(1) # opening fence line, incl. trailing newline
body = m.group(2) # code body (may be empty)
@@ -5735,7 +5738,7 @@ class TelegramAdapter(BasePlatformAdapter):
return _ph(opening + body + closing)
text = re.sub(
- r'(?m)^([ ]{0,3}`{3}[^\n]*\n)([\s\S]*?)(^[ ]{0,3}`{3})[ \t]*$',
+ r'(?m)^([ ]{0,3}`{3}[^\n]*\n)([\s\S]*?)(^[ ]{0,3}`{3})[ \t]*\r?$',
_protect_fenced,
text,
)
diff --git a/tests/gateway/test_telegram_format.py b/tests/gateway/test_telegram_format.py
index 321adc24888..9e622ffe7f5 100644
--- a/tests/gateway/test_telegram_format.py
+++ b/tests/gateway/test_telegram_format.py
@@ -150,6 +150,20 @@ class TestFormatMessageCodeBlocks:
assert "``````" not in result
assert "code" in result
+ def test_fence_with_crlf_line_endings_is_protected(self, adapter):
+ r"""A fenced block whose lines end in CRLF (``\r\n``) — e.g. content
+ that originated on Windows — must still be protected. The closing-fence
+ anchor tolerates a trailing ``\r`` before the line end; without it the
+ block goes unrecognized and its backticks are escaped into literal
+ ``\``` runs, dropping the code formatting."""
+ text = "```\r\ncode\r\n```\r\n"
+ result = adapter.format_message(text)
+ # Protected as a real fence: the body survives and the fence backticks
+ # are emitted literally, not escaped (which is what an unmatched close
+ # would produce).
+ assert "code" in result
+ assert "\\`" not in result
+
@pytest.mark.asyncio
async def test_final_send_does_not_retrigger_typing(adapter):