diff --git a/plugins/platforms/telegram/rich_code_regions.py b/plugins/platforms/telegram/rich_code_regions.py new file mode 100644 index 0000000000..2d12c8b1b7 --- /dev/null +++ b/plugins/platforms/telegram/rich_code_regions.py @@ -0,0 +1,151 @@ +"""Code regions of a rich-message markdown text, found in one linear pass. + +Text inside code is shown verbatim (CommonMark backslash escapes do not apply there), so a pass +that rewrites prose (the currency ``$`` escape, unrenderable-link degrading) must skip it. A +backreference regex (``(`+).*?\\1``) rescans to the end of the line from every backtick run that +has no same-width closer, which made a 32 KB line of mismatched runs block the gateway event loop +for seconds (#151725), and it only knew closed ``` fences and single-line spans. +""" + +import re +from bisect import bisect_left + +# Quote and list markers a fence may sit behind ("> ```", "- ```", "1. ```"). +_BLOCK_PREFIX = r"[ \t]*(?:(?:>[ \t]*|[-+*][ \t]+|\d+[.)][ \t]+))*" +_FENCE_OPEN_RE = re.compile(_BLOCK_PREFIX + r"(?P`{3,}(?![^`\n]*`)|~{3,})") +# Models also open a fence after lead-in prose ("Here is the code: ```bash"); the MarkdownV2 path +# reads that as a fence too, so its body must not be rewritten here either. +_LEADIN_FENCE_RE = re.compile(r"(?:(?!```)[^\n])*(?P`{3,})[^`\n]*$") +_FENCE_CLOSE_RE = re.compile(_BLOCK_PREFIX + r"(?P`{3,}|~{3,})[ \t]*\r?$") +_LIST_ITEM_RE = re.compile(r"[ \t]*(?:[-+*]|\d+[.)])[ \t]") +_INDENTED_RE = re.compile(r"(?: {4}| {0,3}\t)") +_BACKTICK_RUN_RE = re.compile(r"`+") +_HTML_CODE_OPEN_RE = re.compile(r"<(pre|code)\b[^<>\n]*>", re.IGNORECASE) +_HTML_CODE_CLOSE_RE = re.compile(r"", re.IGNORECASE) +_BLANK_LINE_RE = re.compile(r"\n[ \t]*(?=\n)") + + +def _line_spans(text: str): + """``(start, end)`` of every line, ``end`` excluding its newline.""" + start = 0 + for m in re.finditer("\n", text): + yield start, m.start() + start = m.end() + yield start, len(text) + + +def _block_regions(text: str) -> list: + """Fenced blocks (``` or ~~~, closed by a fence of the same char at least as long, or open to + the end of the text as in a streamed draft) and indented code blocks.""" + regions: list = [] + fence = None # (char, width, region start) of the open fence + indented_start = None + prev_blank, in_list = True, False + for start, end in _line_spans(text): + line = text[start:end] + if fence is not None: + close = _FENCE_CLOSE_RE.match(line) + if close and close["fence"][0] == fence[0] and len(close["fence"]) >= fence[1]: + regions.append((fence[2], end)) + fence, prev_blank = None, False + continue + blank = not line.strip() + if indented_start is not None and not blank and not _INDENTED_RE.match(line): + regions.append((indented_start, start - 1)) + indented_start = None + opened = _FENCE_OPEN_RE.match(line) or _LEADIN_FENCE_RE.match(line) + if indented_start is None and opened: + fence = (opened["fence"][0], len(opened["fence"]), start + opened.start("fence")) + continue + if indented_start is None and not blank and prev_blank and not in_list and _INDENTED_RE.match(line): + indented_start = start # an indented line can't interrupt a paragraph or a list item + elif not blank and indented_start is None: + in_list = bool(_LIST_ITEM_RE.match(line)) or (in_list and line[:1] in " \t") + prev_blank = blank + if fence is not None: + regions.append((fence[2], len(text))) + elif indented_start is not None: + regions.append((indented_start, len(text))) + return regions + + +def _inline_regions(text: str, lo: int, hi: int, html: bool) -> list: + """Backtick spans and ``
``/```` elements in ``text[lo:hi]``, left to right.
+
+    A backtick run closes at the next run of exactly its width before a blank line (CommonMark);
+    an unclosed run is literal and the scan goes on after it. Each run is indexed once by width,
+    so pairing is a bisect, never a rescan.
+    """
+    runs = [(m.start(), m.end()) for m in _BACKTICK_RUN_RE.finditer(text, lo, hi)]
+    by_width: dict = {}
+    for k, (s, e) in enumerate(runs):
+        by_width.setdefault(e - s, []).append(k)
+    blanks = [m.start() for m in _BLANK_LINE_RE.finditer(text, lo, hi)]
+    closes: dict = {}
+    for m in _HTML_CODE_CLOSE_RE.finditer(text, lo, hi):
+        closes.setdefault(m[1].lower(), []).append(m.start())
+    html = [(m.start(), m.end(), m[1].lower()) for m in _HTML_CODE_OPEN_RE.finditer(text, lo, hi)] if html else []
+
+    regions: list = []
+    pos, k, h = lo, 0, 0
+    while k < len(runs) or h < len(html):
+        if h < len(html) and (k == len(runs) or html[h][0] < runs[k][0]):
+            start, open_end, name = html[h]
+            h += 1
+            if start < pos:
+                continue
+            ends = closes.get(name, [])
+            j = bisect_left(ends, open_end)
+            if j < len(ends):
+                end = text.index(">", ends[j]) + 1
+                regions.append((start, end))
+                pos = end
+            continue
+        s, e = runs[k]
+        k += 1
+        if s < pos:
+            continue
+        same = by_width[e - s]
+        j = bisect_left(same, k)
+        if j == len(same):
+            continue
+        close_start, close_end = runs[same[j]]
+        b = bisect_left(blanks, e)
+        if b < len(blanks) and blanks[b] < close_start:
+            continue  # a code span ends with its paragraph
+        regions.append((s, close_end))
+        pos, k = close_end, same[j] + 1
+    return regions
+
+
+def rich_code_regions(text: str, *, html: bool = True) -> list:
+    """Sorted, disjoint ``(start, end)`` spans of *text* that are code; ``html=False`` leaves
+    ``
``/```` elements out (for a caller that is looking for HTML tags)."""
+    regions, pos = [], 0
+    for start, end in _block_regions(text) + [(len(text), len(text))]:
+        regions.extend(_inline_regions(text, pos, start, html))
+        if end > start:
+            regions.append((start, end))
+        pos = end
+    return regions
+
+
+def map_outside_code(text: str, transform, *, html: bool = True) -> str:
+    """*text* with ``transform`` applied to each stretch between code regions; code is verbatim."""
+    out, pos = [], 0
+    for start, end in rich_code_regions(text, html=html):
+        out.append(transform(text[pos:start]))
+        out.append(text[start:end])
+        pos = end
+    out.append(transform(text[pos:]))
+    return "".join(out)
+
+
+def strip_code(text: str) -> str:
+    """*text* with its Markdown code removed (``
``/```` elements are kept)."""
+    out, pos = [], 0
+    for start, end in rich_code_regions(text, html=False):
+        out.append(text[pos:start])
+        pos = end
+    out.append(text[pos:])
+    return "".join(out)
diff --git a/plugins/platforms/telegram/standalone.py b/plugins/platforms/telegram/standalone.py
index 29d83f547e..274d1caac1 100644
--- a/plugins/platforms/telegram/standalone.py
+++ b/plugins/platforms/telegram/standalone.py
@@ -14,7 +14,7 @@ import re
 from types import SimpleNamespace
 
 from agent.redact import redact_sensitive_text
-from plugins.platforms.telegram.telegram_markdown import _MD_CODE_RE
+from plugins.platforms.telegram.rich_code_regions import strip_code
 from plugins.platforms.telegram.telegram_send_errors import SAME_REQUEST_ATTEMPTS, is_entity_parse_error
 from pm import install_hint
 
@@ -307,7 +307,7 @@ def _telegram_format(message):
     ``format_message``."""
     from telegram.constants import ParseMode
     # A tag shown as Markdown code (any backtick width, as the MarkdownV2 path reads it) is an example.
-    if _TELEGRAM_HTML_TAG_RE.search(_MD_CODE_RE.sub("", message)):
+    if _TELEGRAM_HTML_TAG_RE.search(strip_code(message)):
         return _escape_non_telegram_markup(message), ParseMode.HTML, True
     mdv2 = _telegram_mdv2(message)
     return (message if mdv2 is None else mdv2), ParseMode.MARKDOWN_V2, False  # None: send as-is
diff --git a/plugins/platforms/telegram/telegram_markdown.py b/plugins/platforms/telegram/telegram_markdown.py
index ed55c730a9..97db06d039 100644
--- a/plugins/platforms/telegram/telegram_markdown.py
+++ b/plugins/platforms/telegram/telegram_markdown.py
@@ -4,6 +4,7 @@ import bisect
 import re
 
 from gateway.platforms.helpers import convert_table_to_bullets as _wrap_markdown_tables
+from plugins.platforms.telegram.rich_code_regions import map_outside_code
 
 # Stands in for the ** of a line-start **> expandable-quote opener while emphasis is resolved.
 _EXPANDABLE_QUOTE = "\x00EQ\x00"
@@ -73,19 +74,24 @@ def _resolve_emphasis(text: str, stash, escape) -> str:
     tokens = []  # ("t", s) literal | ["d", start, end, can_open, can_close, remaining, opens, closes]
     pos = 0
     for m in re.finditer(r"\*+", text):
-        if m.start() > pos:
-            tokens.append(("t", text[pos : m.start()]))
-        before = text[m.start() - 1] if m.start() > 0 else ""
+        run_start = m.start()
+        if (run_start - len(text[:run_start].rstrip("\\"))) % 2:
+            run_start += 1  # a backslash-escaped * is literal text (**Use \*args**, #151722)
+            if run_start == m.end():
+                continue
+        if run_start > pos:
+            tokens.append(("t", text[pos:run_start]))
+        before = text[run_start - 1] if run_start > 0 else ""
         after = text[m.end()] if m.end() < len(text) else ""
         can_open = bool(after) and not after.isspace()
         can_close = bool(before) and not before.isspace()
         tokens.append([
             "d",
-            m.start(),
+            run_start,
             m.end(),
             can_open,
             can_close,
-            m.end() - m.start(),
+            m.end() - run_start,
             [],
             [],
         ])
@@ -95,33 +101,83 @@ def _resolve_emphasis(text: str, stash, escape) -> str:
 
     edges = _SpanEdges(text)
     stack = []  # indexes of delimiter tokens that may still close
+    near2 = []  # per stack slot: the slot of the nearest opener at or below it with 2+ stars left
+    bottoms: dict = {}  # (closer length % 3, closer can open) -> token index a failed search reached
     for idx, tok in enumerate(tokens):
         if tok[0] != "d":
             continue
-        _, start, _end, can_open, can_close, remaining, _opens, closes = tok
-        if can_close:
-            while remaining > 0 and stack:
-                opener = tokens[stack[-1]]
-                o_end, o_remaining = opener[2], opener[5]
-                use = 2 if o_remaining >= 2 and remaining >= 2 else 1
-                if use == 1 and edges.has_newline(o_end, start):
-                    break  # italic must not cross a line
-                if use == 2 and (edges.has_blank_line(o_end, start) or edges.crosses_quote_edge(o_end, start)):
-                    break  # bold stays within one paragraph and on one side of a quote's edge
-                kind = "bold" if use == 2 else "italic"
-                opener[6].append((kind, idx))
-                closes.append((kind, stack[-1]))
-                opener[5] = o_remaining - use
-                remaining -= use
-                if opener[5] == 0:
-                    stack.pop()
-        tok[5] = remaining
+        _, _start, _end, can_open, can_close, remaining, _opens, closes = tok
+        while can_close and remaining > 0 and stack:
+            depth = _pick_opener(tokens, stack, near2, tok, bottoms, edges)
+            if depth is None:
+                break
+            del stack[depth + 1:], near2[depth + 1:]  # openers between the pair stay literal (CommonMark)
+            opener = tokens[stack[-1]]
+            use = 2 if opener[5] >= 2 and tok[5] >= 2 else 1
+            kind = "bold" if use == 2 else "italic"
+            opener[6].append((kind, idx))
+            closes.append((kind, stack[-1]))
+            opener[5] -= use
+            tok[5] = remaining = remaining - use
+            if opener[5] == 0:
+                stack.pop()
+                near2.pop()
+            elif opener[5] < 2:
+                near2[-1] = near2[-2] if len(near2) > 1 else -1
         if remaining > 0 and can_open:
             stack.append(idx)
+            near2.append(len(stack) - 1 if remaining >= 2 else (near2[-1] if near2 else -1))
 
     return _render_emphasis(tokens, stash, escape)
 
 
+def _rule_of_three_refuses(opener: list, closer: list) -> bool:
+    """CommonMark's rule of 3: when either run can both open and close, the two may not pair if
+    their lengths sum to a multiple of 3 unless both are multiples of 3. Without it the ``*`` of
+    ``2*3`` closed one star of a ``**`` opener, so ``**2*3 = 6**`` turned italic and lost its
+    ``*`` (#151722)."""
+    o_len, c_len = opener[2] - opener[1], closer[2] - closer[1]
+    return bool(opener[4] or closer[3]) and (o_len + c_len) % 3 == 0 and bool(o_len % 3 or c_len % 3)
+
+
+def _span_allows(edges: "_SpanEdges", opener: list, closer: list) -> bool:
+    """Italic stays on one line; bold stays within one paragraph and on one side of a quote edge."""
+    if opener[5] >= 2 and closer[5] >= 2:
+        return not (edges.has_blank_line(opener[2], closer[1]) or edges.crosses_quote_edge(opener[2], closer[1]))
+    return not edges.has_newline(opener[2], closer[1])
+
+
+def _pick_opener(tokens: list, stack: list, near2: list, closer: list, bottoms: dict, edges):
+    """Stack slot of the opener *closer* pairs with, or ``None``.
+
+    The nearest opener the rule of 3 allows wins, as in CommonMark, except that a bare ``**``
+    closer reaches past single-``*`` openers to a ``**`` opener: chat text means
+    ``**rm -rf *.tmp**`` as bold around a literal ``*`` (CommonMark nests two italics there, which
+    Telegram cannot show, and drops the star). A ``***`` closer still pairs its ``*`` first
+    (``**a *b***``). A failed
+    search records how far down it looked for closers of the same class, so a long run of refused
+    openers is walked once, not once per closer.
+    """
+    key = ((closer[2] - closer[1]) % 3, closer[3])
+    floor = bottoms.get(key, -1)
+    nearest = None
+    for depth in range(len(stack) - 1, -1, -1):
+        if stack[depth] <= floor:
+            break
+        if not _rule_of_three_refuses(tokens[stack[depth]], closer):
+            nearest = depth
+            break
+    if nearest is None:
+        bottoms[key] = stack[-1]
+        return None
+    candidates = [nearest]
+    if closer[2] - closer[1] == closer[5] == 2 and tokens[stack[nearest]][5] < 2 and near2[nearest] >= 0:
+        double = tokens[stack[near2[nearest]]]
+        if not _rule_of_three_refuses(double, closer):
+            candidates.insert(0, near2[nearest])
+    return next((d for d in candidates if _span_allows(edges, tokens[stack[d]], closer)), None)
+
+
 def _crosses_quote_edge(text: str, start: int, end: int) -> bool:
     """True when a newline in text[start:end] borders a quote line: Telegram ends a blockquote at a
     newline into non-quote text, an entity still open there is rejected, and an entity spanning
@@ -195,9 +251,6 @@ def _render_emphasis(tokens: list, stash, escape) -> str:
 _RENDERABLE_LINK_TARGET_RE = re.compile(
     r'(?i)^(?:[a-z][a-z0-9+.-]*:[^\s@]\S*|[a-z0-9-]+(?:\.[a-z0-9-]+)+(?:[/?#:]\S*)?)$')
 _MD_LINK_RE = re.compile(r'\[([^\]]+)\]\(([^()]*(?:\([^()]*\)[^()]*)*)\)')
-# Fences, then inline spans closed by a backtick run of the SAME width (CommonMark, as
-# ``_RICH_DOLLAR_RE``'s code branch): ``a [k](v w)`` is one span, not two empty ones.
-_MD_CODE_RE = re.compile(r'```[\s\S]*?(?:```|$)|(?P`+)[^\n]*?(? bool:
@@ -209,13 +262,7 @@ def degrade_unrenderable_links(markdown: str) -> str:
     spans and fences stay verbatim)."""
     if '](' not in markdown:
         return markdown
-    out, pos = [], 0
-    for code in _MD_CODE_RE.finditer(markdown):
-        out.append(_MD_LINK_RE.sub(_link_or_label, markdown[pos:code.start()]))
-        out.append(code.group(0))
-        pos = code.end()
-    out.append(_MD_LINK_RE.sub(_link_or_label, markdown[pos:]))
-    return ''.join(out)
+    return map_outside_code(markdown, lambda prose: _MD_LINK_RE.sub(_link_or_label, prose))
 
 
 def _link_or_label(m) -> str:
@@ -395,22 +442,22 @@ def _escape_bare_bracket(m, seg: str) -> str:
 # The formula bodies are possessive: none can consume $, so a match ends a body at the first
 # character it can't take, and a failed span must not retry every split of a TeX command (the
 # escape runs on the gateway event loop for every streamed draft frame).
-# Regions the rich-message dollar escape leaves verbatim (fenced code, inline code delimited by
-# matching backtick-run widths, $$ display math, $x$ inline math, digit-led formulas such as $2+2$
+# Regions the rich-message dollar escape leaves verbatim (code is skipped before this runs, see
+# ``rich_code_regions``; $$ display math, $x$ inline math, digit-led formulas such as $2+2$
 # that carry an operator or close tight like $4$ (an amount is never closed by a $ that no digit or
 # word follows), spaced formulas such as $2x + 1$, $2\,x$ or $5! = 120$ (any symbol but . , and `,
-# or a TeX command; letters only as one-letter variables, so "$5 or 10$" and "$5 - $3" stay prose:
+# or a TeX command, whose {...} arguments may hold words ($1\text{ kg}$); letters only as one-letter variables, so "$5 or 10$" and "$5 - $3" stay prose:
 # the closing $ is never followed by a digit, so an amount's $ cannot close it), already-escaped \$),
 # and the currency $ it escapes: a lone $ before an
 # amount, or after a currency prefix (R$ 1.000, US$ 1,200). Telegram's rich Markdown pairs any two
 # bare $ as inline LaTeX, so "$395k vs $483k" otherwise renders as one garbled math span.
 _RICH_DOLLAR_RE = re.compile(
-    r'(?P```[\s\S]*?```|(?P`+)[^\n]*?(?\\\$|\$\$[\s\S]*?\$\$'
     r'|(?]|\\[a-zA-Z]++)(?:[\w.,(){}^_+*/=<>-]|\\[a-zA-Z]+)*+(?])\$(?![\w$])'
     r'|(?\s])\$(?![\w$]|\s?\d))'
+    r'(?:\\[a-zA-Z]+(?:\{[^{}$\n\\]*\})*+|\\[^a-zA-Z\s$]|[^\W\d_](?![^\W\d_])|[^$\n\\\w`]|[\d_])*+(?\s])\$(?![\w$]|\s?\d))'
     r'|(?P(? str:
     """Escape currency ``$`` for ``sendRichMessage`` markdown; real math, code and ``\\$`` are kept."""
     if '$' not in text:
         return text
-    return _RICH_DOLLAR_RE.sub(lambda m: m.group(0) if m.group('keep') else '\\$', text)
+    return map_outside_code(text, _escape_prose_dollars)
+
+
+def _escape_prose_dollars(prose: str) -> str:
+    if '$' not in prose:
+        return prose
+    return _RICH_DOLLAR_RE.sub(lambda m: m.group(0) if m.group('keep') else '\\$', prose)
diff --git a/tests/plugins/platforms/telegram/test_telegram_markdown_150997_regressions.py b/tests/plugins/platforms/telegram/test_telegram_markdown_150997_regressions.py
new file mode 100644
index 0000000000..b792971251
--- /dev/null
+++ b/tests/plugins/platforms/telegram/test_telegram_markdown_150997_regressions.py
@@ -0,0 +1,64 @@
+"""Regressions from #150997: emphasis rule of 3 (#151722) and the rich-message code-region scan
+(#151725). Exact outputs are judged by the Bot API stand-in's MarkdownV2 parser too."""
+
+import time
+
+import pytest
+
+from gateway.config import PlatformConfig
+from plugins.platforms.telegram.adapter import TelegramAdapter
+from plugins.platforms.telegram.telegram_markdown import escape_rich_currency_dollars
+from tests.fakes.platforms.telegram_standin import mdv2_error
+
+
+@pytest.fixture()
+def adapter() -> TelegramAdapter:
+    return TelegramAdapter(PlatformConfig(enabled=True, token="123:abc"))
+
+
+@pytest.mark.parametrize(
+    ("markdown", "expected"),
+    [
+        ("**Result: 2*3 = 6**", "*Result: 2\\*3 \\= 6*"),
+        ("The answer is **6*7 = 42**.", "The answer is *6\\*7 \\= 42*\\."),
+        ("**rm -rf *.tmp**", "*rm \\-rf \\*\\.tmp*"),
+        ("**glob *.py files**", "*glob \\*\\.py files*"),
+        ("*a**b**c*", "_a*b*c_"),
+        ("**Use \\*args**", "*Use \\\\\\*args*"),
+    ],
+)
+def test_a_lone_star_inside_bold_stays_a_visible_star(adapter, markdown, expected):
+    """A ``*`` flanked by text inside ``**bold**`` is literal: bold stays bold and no character of
+    the user's math or shell command disappears (#151722)."""
+    out = adapter.format_message(markdown)
+    assert out == expected
+    assert mdv2_error(out) is None
+
+
+@pytest.mark.parametrize(
+    ("markdown", "expected"),
+    [
+        # A fence still streaming (no closing fence yet) is code to the end of the text.
+        ("```bash\necho $5\n", "```bash\necho $5\n"),
+        ("~~~\necho $5\n~~~\nthen $6", "~~~\necho $5\n~~~\nthen \\$6"),
+        ("````\n```\n$5\n```\n````\n$6", "````\n```\n$5\n```\n````\n\\$6"),
+        ("text\n\n    echo $5\n\nthen $6", "text\n\n    echo $5\n\nthen \\$6"),
+        ("$5 and $6", "$5 and \\$6"),
+        # The closer pairs with the next run of the opener's width, not a shorter tail.
+        ("x ``y` $5 z` w", "x ``y` $5 z` w"),
+        ("$1\\text{ kg}$ and $x$", "$1\\text{ kg}$ and $x$"),
+    ],
+)
+def test_rich_dollar_escape_leaves_every_code_region_verbatim(markdown, expected):
+    """CommonMark applies no backslash escape inside code, so an inserted ``\\$`` would show (#151725)."""
+    assert escape_rich_currency_dollars(markdown) == expected
+
+
+def test_rich_payload_is_linear_on_unmatched_backtick_runs(adapter):
+    """#151725: every backtick run without a same-width closer rescanned the rest of the line, so
+    this 32 KB reply blocked the gateway event loop for ~2 s on every rich send and draft frame."""
+    text = "$5 " + "``x```" * 5400
+    started = time.perf_counter()
+    payload = adapter._rich_message_payload(text)
+    assert time.perf_counter() - started < 1.0
+    assert payload["markdown"].startswith("\\$5 ")