block_kit.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. """Render agent markdown into Slack Block Kit blocks.
  2. Opt-in (``slack.extra.rich_blocks: true``) alternative to the flat mrkdwn
  3. ``text`` payload produced by :meth:`SlackAdapter.format_message`. Block Kit
  4. gives us real structural primitives — section headers, dividers, and true
  5. *nested* lists via ``rich_text`` — that plain mrkdwn can only approximate.
  6. Design constraints (why this module is deliberately conservative):
  7. * **Markdown pipe-tables render as native ``table`` blocks** — real grid
  8. cells with per-column alignment and inline-formatted ``rich_text`` content.
  9. A table that exceeds Slack's limits (100 rows / 20 cols / 10k aggregate
  10. cell chars) or won't parse falls back to aligned monospace
  11. ``rich_text_preformatted`` so a large table never breaks the message.
  12. * **Slack caps a message at 50 blocks** and a ``section``/text object at 3000
  13. characters. :func:`render_blocks` enforces both and, if the content simply
  14. cannot be expressed within them, returns ``None`` so the caller falls back
  15. to the plain-text path. A rich render is a nice-to-have; it must never lose
  16. a message.
  17. * **Every blocks payload MUST ship a ``text`` fallback.** Slack uses it for
  18. notifications, screen readers, and old clients. This module only builds the
  19. ``blocks`` list; the adapter pairs it with the existing mrkdwn string.
  20. The renderer never raises: any unexpected input degrades to ``None`` (caller
  21. uses plain text). It is a pure function of its input — no Slack client, no
  22. adapter state — so it is trivially unit-testable.
  23. """
  24. from __future__ import annotations
  25. import re
  26. from typing import Any, Dict, List, Optional, Tuple
  27. # Slack Block Kit hard limits (https://docs.slack.dev/reference/block-kit/blocks)
  28. MAX_BLOCKS = 50
  29. MAX_SECTION_TEXT = 3000
  30. MAX_HEADER_TEXT = 150
  31. # Native table block limits (https://docs.slack.dev/reference/block-kit/blocks/table-block)
  32. MAX_TABLE_ROWS = 100
  33. MAX_TABLE_COLS = 20
  34. MAX_TABLE_CHARS = 10000 # aggregate across all cells
  35. Block = dict[str, Any]
  36. # ----------------------------------------------------------------------------
  37. # Line classification
  38. # ----------------------------------------------------------------------------
  39. _HR_RE = re.compile(r"^\s{0,3}([-*_])(?:\s*\1){2,}\s*$")
  40. _HEADER_RE = re.compile(r"^\s{0,3}(#{1,6})\s+(.+?)\s*#*\s*$")
  41. _FENCE_RE = re.compile(r"^\s*(`{3,}|~{3,})(.*)$")
  42. _ORDERED_RE = re.compile(r"^(\s*)(\d+)[.)]\s+(.*)$")
  43. _BULLET_RE = re.compile(r"^(\s*)[-*+]\s+(.*)$")
  44. _QUOTE_RE = re.compile(r"^\s{0,3}>\s?(.*)$")
  45. _TABLE_SEP_RE = re.compile(r"^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)+\|?\s*$")
  46. def _is_list_line(line: str) -> bool:
  47. """True if ``line`` is a markdown list item (bullet or ordered)."""
  48. return bool(_BULLET_RE.match(line) or _ORDERED_RE.match(line))
  49. def _indent_level(spaces: str) -> int:
  50. """Map leading whitespace to a nesting level (2 spaces or 1 tab per level)."""
  51. width = 0
  52. for ch in spaces:
  53. width += 4 if ch == "\t" else 1
  54. return min(width // 2, 5) # Slack rich_text_list supports up to indent 5
  55. # ----------------------------------------------------------------------------
  56. # Inline markdown → rich_text elements
  57. # ----------------------------------------------------------------------------
  58. # Order matters: code first (opaque), then links, then emphasis.
  59. _INLINE_CODE_RE = re.compile(r"`([^`]+)`")
  60. _LINK_RE = re.compile(r"(?<!!)\[([^\]]+)\]\(([^()\s]+(?:\([^()]*\)[^()\s]*)*)\)")
  61. # Slack mrkdwn autolink: <scheme:target> or <scheme:target|label>.
  62. _SLACK_LINK_RE = re.compile(
  63. r"<([a-zA-Z][a-zA-Z0-9+.\-]*:[^>|]+)(?:\|([^>]+))?>"
  64. )
  65. # Slack mention tokens carry no scheme: <@U…> (user), <#C…> (channel, with an
  66. # optional |name label), <!subteam^S…> (usergroup) and <!here|!channel|!everyone>
  67. # (broadcast). rich_text does not interpret mrkdwn, so these must become
  68. # user/channel/broadcast/usergroup elements — as plain text Slack renders the
  69. # token literally.
  70. _SLACK_MENTION_RE = re.compile(
  71. r"<(@[A-Z0-9]+|#[A-Z0-9]+|!subteam\^[A-Z0-9]+|!(?:here|channel|everyone))(?:\|[^>]*)?>"
  72. )
  73. _BOLD_RE = re.compile(r"(?:\*\*|__)(.+?)(?:\*\*|__)")
  74. _ITALIC_RE = re.compile(r"(?<![\*_])(?:\*|_)(?![\*_\s])(.+?)(?<![\*_\s])(?:\*|_)(?![\*_])")
  75. _STRIKE_RE = re.compile(r"~~(.+?)~~")
  76. def _mention_element(body: str) -> Optional[dict[str, Any]]:
  77. """Map a Slack mention token body (without the angle brackets) to a rich_text element.
  78. ``@U…`` -> user, ``#C…`` -> channel, ``!subteam^S…`` -> usergroup,
  79. ``!here``/``!channel``/``!everyone`` -> broadcast.
  80. Returns None for anything else, so the caller can emit the raw token as text."""
  81. if body.startswith("@"):
  82. return {"type": "user", "user_id": body[1:]}
  83. if body.startswith("#"):
  84. return {"type": "channel", "channel_id": body[1:]}
  85. if body.startswith("!subteam^"):
  86. return {"type": "usergroup", "usergroup_id": body[len("!subteam^"):]}
  87. if body.startswith("!"):
  88. return {"type": "broadcast", "range": body[1:]}
  89. return None
  90. def _inline_elements(text: str) -> list[dict[str, Any]]:
  91. """Parse a run of inline markdown into rich_text section child elements.
  92. Produces ``text`` elements (optionally styled bold/italic/strike/code) and ``link`` elements.
  93. Unmatched markup is emitted verbatim as plain text, so this never loses characters."""
  94. elements: list[dict[str, Any]] = []
  95. def emit_text(s: str, style: Optional[dict[str, bool]] = None) -> None:
  96. if not s:
  97. return
  98. el: dict[str, Any] = {"type": "text", "text": s}
  99. if style:
  100. el["style"] = style
  101. elements.append(el)
  102. # Tokenize by the highest-priority markers first using a single scan.
  103. # We recursively split on code, then links, then emphasis to keep spans
  104. # from overlapping incorrectly.
  105. def walk(s: str, style: dict[str, bool]) -> None:
  106. pos = 0
  107. # inline code is opaque — no nested styling
  108. for m in _INLINE_CODE_RE.finditer(s):
  109. _walk_links(s[pos : m.start()], style)
  110. emit_text(m.group(1), {**style, "code": True})
  111. pos = m.end()
  112. _walk_links(s[pos:], style)
  113. def _emit_link(url: str, text: str, style: dict[str, bool]) -> None:
  114. link_el: dict[str, Any] = {"type": "link", "url": url, "text": text}
  115. if style:
  116. link_el["style"] = dict(style)
  117. elements.append(link_el)
  118. def _walk_links(s: str, style: dict[str, bool]) -> None:
  119. pos = 0
  120. for m in _LINK_RE.finditer(s):
  121. _walk_slack_links(s[pos : m.start()], style)
  122. _emit_link(m.group(2), m.group(1), style)
  123. pos = m.end()
  124. _walk_slack_links(s[pos:], style)
  125. def _walk_slack_links(s: str, style: dict[str, bool]) -> None:
  126. # rich_text does not interpret mrkdwn. Agents often emit <url|label>
  127. # (works in section/mrkdwn; was literal in lists/quotes/table cells).
  128. # Mention labels are dropped from the element anyway; strip them first
  129. # so a label like |dev_ops_alerts is not split by the italic regex.
  130. s = _SLACK_MENTION_RE.sub(lambda m: f"<{m.group(1)}>", s)
  131. pos = 0
  132. for m in _SLACK_LINK_RE.finditer(s):
  133. _walk_emphasis(s[pos : m.start()], style)
  134. url = m.group(1)
  135. _emit_link(url, m.group(2) or url, style)
  136. pos = m.end()
  137. _walk_emphasis(s[pos:], style)
  138. def _walk_emphasis(s: str, style: dict[str, bool]) -> None:
  139. if not s:
  140. return
  141. # Try bold, then strike, then italic, recursing into the inner span.
  142. for rx, key in ((_BOLD_RE, "bold"), (_STRIKE_RE, "strike"), (_ITALIC_RE, "italic")):
  143. m = rx.search(s)
  144. if m:
  145. _walk_emphasis(s[: m.start()], style)
  146. inner_style = dict(style)
  147. inner_style[key] = True
  148. _walk_emphasis(m.group(1), inner_style)
  149. _walk_emphasis(s[m.end() :], style)
  150. return
  151. # Base case: split on mention tokens at the leaf so emphasis spans
  152. # wrapping a mention are kept intact, while mentions themselves
  153. # remain unstyled (Slack rejects styled mention elements).
  154. pos = 0
  155. for m in _SLACK_MENTION_RE.finditer(s):
  156. emit_text(s[pos : m.start()], dict(style) if style else None)
  157. element = _mention_element(m.group(1))
  158. if element is not None:
  159. elements.append(element)
  160. else:
  161. emit_text(m.group(0), dict(style) if style else None)
  162. pos = m.end()
  163. emit_text(s[pos:], dict(style) if style else None)
  164. walk(text, {})
  165. return elements or [{"type": "text", "text": text}]
  166. # ----------------------------------------------------------------------------
  167. # Structural block builders
  168. # ----------------------------------------------------------------------------
  169. def _nonempty_elements(elements: list[dict[str, Any]]) -> list[dict[str, Any]]:
  170. """Make a rich_text child-element list safe for Slack.
  171. Slack rejects any ``rich_text_section`` / ``rich_text_preformatted`` / ``rich_text_quote`` whose
  172. ``elements`` list is empty or contains a ``text`` element of zero length (``invalid_blocks``:
  173. "missing element" / "must be more than 0 characters"). Empty content is common — ragged table
  174. rows are padded with ``""``, agents emit empty code fences around empty tool output, blank quote
  175. lines and empty list items occur in the wild — so drop zero-length text elements and, if nothing
  176. remains, substitute a single space, which renders as blank yet stays schema-valid. Used by every
  177. rich_text builder so empty content can never poison the whole payload."""
  178. els = [e for e in elements if not (e.get("type") == "text" and not e.get("text"))]
  179. return els or [{"type": "text", "text": " "}]
  180. def _header_block(text: str) -> Optional[Block]:
  181. # header blocks are plain_text only, 150 char cap.
  182. clean = re.sub(r"[*_~`]", "", text).strip()
  183. if not clean:
  184. # Emphasis-/whitespace-only header (e.g. "# ***" or "# ") reduces to
  185. # empty; Slack rejects an empty plain_text with invalid_blocks. Skip it
  186. # (caller drops None) rather than poison the whole payload.
  187. return None
  188. if len(clean) > MAX_HEADER_TEXT:
  189. clean = clean[: MAX_HEADER_TEXT - 1] + "…"
  190. return {"type": "header", "text": {"type": "plain_text", "text": clean, "emoji": True}}
  191. def _divider_block() -> Block:
  192. return {"type": "divider"}
  193. def _rich_text_block(kind: str, children: list[dict[str, Any]]) -> Block:
  194. """One ``rich_text`` block wrapping a single ``kind`` element (section/quote/preformatted)."""
  195. return {
  196. "type": "rich_text", "elements": [{"type": kind, "elements": _nonempty_elements(children)}]}
  197. def _preformatted_block(text: str) -> Block:
  198. # rich_text_preformatted renders monospace; used for code fences + tables.
  199. return _rich_text_block("rich_text_preformatted", [{"type": "text", "text": text.rstrip("\n")}])
  200. def _quote_block(lines: list[str]) -> Block:
  201. section_children: list[dict[str, Any]] = []
  202. for i, ln in enumerate(lines):
  203. if i:
  204. section_children.append({"type": "text", "text": "\n"})
  205. section_children.extend(_inline_elements(ln))
  206. return _rich_text_block("rich_text_quote", section_children)
  207. def _list_block(items: list[tuple[int, bool, str]]) -> Block:
  208. """Build ONE rich_text block from consecutive list items.
  209. ``items`` is a list of ``(indent, ordered, text)``. Each contiguous run sharing the same
  210. (indent, ordered) becomes a ``rich_text_list`` element; indentation changes start a new element,
  211. which is how Slack renders true nesting."""
  212. elements: list[dict[str, Any]] = []
  213. cur: Optional[dict[str, Any]] = None
  214. cur_key: Optional[tuple[int, bool]] = None
  215. for indent, ordered, text in items:
  216. key = (indent, ordered)
  217. if key != cur_key:
  218. cur = {
  219. "type": "rich_text_list", "style": "ordered" if ordered else "bullet",
  220. "indent": indent, "elements": []}
  221. elements.append(cur)
  222. cur_key = key
  223. cur["elements"].append(
  224. {"type": "rich_text_section", "elements": _nonempty_elements(_inline_elements(text))})
  225. return {"type": "rich_text", "elements": elements}
  226. def _section_block(text: str) -> Block:
  227. return {"type": "section", "text": {"type": "mrkdwn", "text": text}}
  228. # ----------------------------------------------------------------------------
  229. # Table handling — native Block Kit ``table`` block, monospace fallback
  230. # ----------------------------------------------------------------------------
  231. def _parse_alignment(sep_line: str) -> list[str]:
  232. """Parse a markdown separator row (``|:--|:-:|--:|``) into column aligns.
  233. Returns a list of ``"left"``/``"center"``/``"right"`` per column."""
  234. aligns: list[str] = []
  235. for cell in sep_line.strip().strip("|").split("|"):
  236. c = cell.strip()
  237. left, right = c.startswith(":"), c.endswith(":")
  238. aligns.append("center" if left and right else "right" if right else "left")
  239. return aligns
  240. def _split_row(row: str) -> list[str]:
  241. """Split a markdown table row into trimmed cell strings.
  242. Respects backslash-escaped pipes (``\\|``) so they aren't treated as column separators."""
  243. # Temporarily protect escaped pipes, split on real ones, then restore.
  244. protected = row.strip().strip("|").replace(r"\|", "\x00PIPE\x00")
  245. return [c.strip().replace("\x00PIPE\x00", "|") for c in protected.split("|")]
  246. def _rich_text_cell(text: str) -> dict[str, Any]:
  247. """A ``rich_text`` table cell carrying inline-formatted content.
  248. Empty cells are common (ragged rows are padded with ``""``); Slack rejects a cell whose section
  249. is empty or carries a zero-length text element, so the elements are routed through
  250. ``_nonempty_elements``."""
  251. return _rich_text_block("rich_text_section", _inline_elements(text))
  252. def _table_block(rows: list[str], sep_line: str) -> Optional[Block]:
  253. """Build a native Slack ``table`` block from markdown pipe-table rows.
  254. ``rows`` includes the header row (index 0) and body rows; ``sep_line`` is the ``|---|``
  255. alignment row (already consumed by the caller). Returns ``None`` when the table exceeds Slack's
  256. limits (100 rows / 20 cols / 10,000 aggregate cell chars) or parses to nothing — the caller then
  257. falls back to the monospace preformatted rendering."""
  258. parsed = [_split_row(r) for r in rows if r.strip()]
  259. if not parsed:
  260. return None
  261. ncols = max(len(r) for r in parsed)
  262. # Reject rather than silently truncate beyond Slack's structural limits.
  263. if len(parsed) > MAX_TABLE_ROWS or ncols > MAX_TABLE_COLS:
  264. return None
  265. for r in parsed:
  266. r.extend([""] * (ncols - len(r)))
  267. total_chars = sum(len(c) for r in parsed for c in r)
  268. if total_chars > MAX_TABLE_CHARS:
  269. return None
  270. aligns = _parse_alignment(sep_line)
  271. # Slack requires every provided ``column_settings`` entry to be an object.
  272. # Missing trailing entries inherit defaults, so only emit settings through
  273. # the last non-default alignment. Earlier default-left placeholders still
  274. # need explicit valid objects to preserve positional alignment.
  275. padded = [aligns[c] if c < len(aligns) else "left" for c in range(ncols)]
  276. last_non_default = max((c for c, a in enumerate(padded) if a != "left"), default=-1)
  277. column_settings = [{"align": a} for a in padded[: last_non_default + 1]]
  278. block: Block = {
  279. "type": "table", "rows": [[_rich_text_cell(cell) for cell in row] for row in parsed]}
  280. if column_settings:
  281. block["column_settings"] = column_settings
  282. return block
  283. def _render_table(rows: list[str]) -> str:
  284. """Render markdown pipe-table rows as aligned monospace text (fallback)."""
  285. parsed = [_split_row(r) for r in rows]
  286. if not parsed:
  287. return "\n".join(rows)
  288. ncols = max(len(r) for r in parsed)
  289. for r in parsed:
  290. r.extend([""] * (ncols - len(r)))
  291. widths = [max(len(r[c]) for r in parsed) for c in range(ncols)]
  292. out_lines = []
  293. for ri, r in enumerate(parsed):
  294. line = " | ".join(r[c].ljust(widths[c]) for c in range(ncols))
  295. out_lines.append(line.rstrip())
  296. if ri == 0: # header underline
  297. out_lines.append("-+-".join("-" * widths[c] for c in range(ncols)))
  298. return "\n".join(out_lines)
  299. # ----------------------------------------------------------------------------
  300. # Public entry point
  301. # ----------------------------------------------------------------------------
  302. def render_blocks(markdown: str, mrkdwn_fn=None) -> Optional[list[Block]]:
  303. """Convert agent markdown to a Slack Block Kit ``blocks`` list.
  304. Args:
  305. markdown: The agent's response text (standard markdown).
  306. mrkdwn_fn: Optional callable converting a markdown paragraph to Slack
  307. mrkdwn for ``section`` blocks (the adapter passes
  308. ``format_message``). When ``None``, the raw paragraph text is used.
  309. Returns:
  310. A list of Block Kit block dicts, or ``None`` when the content is empty,
  311. exceeds Slack's structural limits, or hits an unexpected shape — the
  312. caller then falls back to the flat ``text`` payload. Never raises."""
  313. if not markdown or not markdown.strip():
  314. return None
  315. fmt = mrkdwn_fn or (lambda s: s)
  316. try:
  317. blocks: list[Block] = []
  318. lines = markdown.replace("\r\n", "\n").split("\n")
  319. i = 0
  320. n = len(lines)
  321. para: list[str] = []
  322. def flush_para() -> None:
  323. if not para:
  324. return
  325. text = "\n".join(para).strip()
  326. para.clear()
  327. if not text:
  328. return
  329. rendered = fmt(text)
  330. # Split oversized sections on the 3000-char limit.
  331. for chunk in _split_text(rendered, MAX_SECTION_TEXT):
  332. blocks.append(_section_block(chunk))
  333. while i < n:
  334. line = lines[i]
  335. # Blank line: paragraph boundary
  336. if not line.strip():
  337. flush_para()
  338. i += 1
  339. continue
  340. # Fenced code block
  341. fence = _FENCE_RE.match(line)
  342. if fence:
  343. flush_para()
  344. marker = fence.group(1)
  345. body: list[str] = []
  346. i += 1
  347. while i < n and not lines[i].lstrip().startswith(marker):
  348. body.append(lines[i])
  349. i += 1
  350. i += 1 # consume closing fence
  351. blocks.append(_preformatted_block("\n".join(body)))
  352. continue
  353. # Horizontal rule → divider
  354. if _HR_RE.match(line):
  355. flush_para()
  356. blocks.append(_divider_block())
  357. i += 1
  358. continue
  359. # ATX header
  360. hm = _HEADER_RE.match(line)
  361. if hm:
  362. flush_para()
  363. header = _header_block(hm.group(2))
  364. if header is not None:
  365. blocks.append(header)
  366. i += 1
  367. continue
  368. # Pipe table: current line has a pipe AND next line is a separator
  369. if "|" in line and i + 1 < n and _TABLE_SEP_RE.match(lines[i + 1]):
  370. flush_para()
  371. header_row = line
  372. sep_line = lines[i + 1]
  373. trows = [header_row]
  374. i += 2 # skip header + separator
  375. while i < n and "|" in lines[i] and lines[i].strip():
  376. trows.append(lines[i])
  377. i += 1
  378. # Prefer a native Block Kit table; fall back to aligned
  379. # monospace when it exceeds Slack's table limits or won't parse.
  380. table = _table_block(trows, sep_line)
  381. if table is not None:
  382. blocks.append(table)
  383. else:
  384. blocks.append(_preformatted_block(_render_table(trows)))
  385. continue
  386. # Blockquote group
  387. if _QUOTE_RE.match(line):
  388. flush_para()
  389. qlines: list[str] = []
  390. while i < n:
  391. qm = _QUOTE_RE.match(lines[i])
  392. if not qm:
  393. break
  394. qlines.append(qm.group(1))
  395. i += 1
  396. blocks.append(_quote_block(qlines))
  397. continue
  398. # List group (bullets + ordered, with nesting)
  399. if _is_list_line(line):
  400. flush_para()
  401. items: list[tuple[int, bool, str]] = []
  402. while i < n:
  403. bm = _BULLET_RE.match(lines[i])
  404. om = _ORDERED_RE.match(lines[i])
  405. if bm:
  406. items.append((_indent_level(bm.group(1)), False, bm.group(2)))
  407. i += 1
  408. elif om:
  409. items.append((_indent_level(om.group(1)), True, om.group(3)))
  410. i += 1
  411. elif lines[i].strip() and lines[i].startswith((" ", "\t")) and items:
  412. # continuation line of the previous item
  413. indent, ordered, txt = items[-1]
  414. items[-1] = (indent, ordered, txt + " " + lines[i].strip())
  415. i += 1
  416. elif not lines[i].strip() and items:
  417. # Blank line inside a list run. LLM-authored ordered
  418. # lists commonly separate items with a blank line; if
  419. # the next non-blank line is another list item, treat
  420. # the blank(s) as a soft separator and keep the run
  421. # going so the items stay in one rich_text_list (Slack
  422. # numbers each list independently, so splitting would
  423. # restart every item at "1."). Otherwise the blank
  424. # ends the list.
  425. j = i + 1
  426. while j < n and not lines[j].strip():
  427. j += 1
  428. if j < n and _is_list_line(lines[j]):
  429. i = j
  430. else:
  431. break
  432. else:
  433. break
  434. blocks.append(_list_block(items))
  435. continue
  436. # Default: accumulate into a paragraph
  437. para.append(line)
  438. i += 1
  439. flush_para()
  440. if not blocks:
  441. return None
  442. if len(blocks) > MAX_BLOCKS:
  443. # Too structurally complex to express safely — let the caller fall
  444. # back to plain text rather than truncating and losing content.
  445. return None
  446. return blocks
  447. except Exception:
  448. # Never let a rendering bug drop a message.
  449. return None
  450. def _split_text(text: str, limit: int) -> list[str]:
  451. """Split ``text`` into <= ``limit``-char chunks on line, then hard, boundaries.
  452. Chunks are fence-balanced: when a split lands inside a ``` code span that survived into section
  453. text (the renderer normally routes fenced blocks to ``rich_text_preformatted``, but mrkdwn text
  454. can still carry fences), the fence is closed at the end of the chunk and reopened on the next so
  455. each section renders correctly on its own."""
  456. if len(text) <= limit:
  457. return [text]
  458. # Reserve headroom for the close/reopen markers the balancing pass adds.
  459. split_limit = max(limit - 8, limit // 2, 1) if "```" in text else limit
  460. out: list[str] = []
  461. remaining = text
  462. while len(remaining) > split_limit:
  463. cut = remaining.rfind("\n", 0, split_limit)
  464. if cut <= 0:
  465. cut = split_limit
  466. out.append(remaining[:cut])
  467. remaining = remaining[cut:].lstrip("\n")
  468. if remaining:
  469. out.append(remaining)
  470. if len(out) > 1 and "```" in text:
  471. balanced: list[str] = []
  472. reopen = False
  473. for chunk in out:
  474. if reopen:
  475. chunk = "```\n" + chunk
  476. odd = chunk.count("```") % 2 == 1
  477. if odd:
  478. chunk += "\n```"
  479. reopen = odd
  480. balanced.append(chunk)
  481. out = balanced
  482. return out
  483. # ----------------------------------------------------------------------------
  484. # Outbound payload boundary — last-resort clamp before the Slack API
  485. # ----------------------------------------------------------------------------
  486. def _clamp_text_obj(text_obj: dict[str, Any], limit: int) -> dict[str, Any]:
  487. """Return ``text_obj`` with its ``text`` clamped to ``limit`` chars."""
  488. txt = text_obj.get("text") or ""
  489. if len(txt) <= limit:
  490. return text_obj
  491. clamped = dict(text_obj)
  492. clamped["text"] = txt[: limit - 1].rstrip() + "…"
  493. return clamped
  494. def sanitize_blocks(blocks: Optional[list[Block]]) -> Optional[list[Block]]:
  495. """Clamp an outbound ``blocks`` payload to Slack's hard limits.
  496. Defensive boundary applied wherever the adapter attaches ``blocks`` to
  497. ``chat.postMessage`` / ``chat.update``. One oversized or malformed block
  498. fails the WHOLE call with ``invalid_blocks`` — approval cards then never
  499. update and messages silently drop — so instead of trusting every builder,
  500. the payload is normalized just before the API call:
  501. * ``section`` / ``context`` text objects are truncated to the 3000-char
  502. cap with an ellipsis (Slack HTML-escapes ``< > &`` on storage, so text
  503. echoed back through interaction payloads can exceed the limit that the
  504. send path originally budgeted for — see #53693 / #62054).
  505. * ``header`` text is truncated to its 150-char cap.
  506. * Empty blocks (no text / no elements / no rows) are dropped — Slack
  507. rejects zero-length text objects and empty element lists.
  508. * ``table.column_settings`` entries must all be objects; ``null`` entries
  509. (emitted by older renderers, per the "use null to skip" misreading of
  510. the schema) are replaced with ``{}`` and default trailing entries are
  511. trimmed (#56615).
  512. * The payload is capped at Slack's 50-block maximum.
  513. Returns the sanitized list, or ``None`` when nothing valid remains — the
  514. caller then sends the plain ``text`` fallback alone. Never raises."""
  515. if not blocks:
  516. return None
  517. try:
  518. out: list[Block] = []
  519. for block in blocks:
  520. if not isinstance(block, dict) or not block.get("type"):
  521. continue
  522. btype = block["type"]
  523. if btype == "section":
  524. text_obj = block.get("text")
  525. has_body = bool(block.get("fields")) or bool(block.get("accessory"))
  526. if isinstance(text_obj, dict):
  527. if not (text_obj.get("text") or "").strip() and not has_body:
  528. continue
  529. clamped = _clamp_text_obj(text_obj, MAX_SECTION_TEXT)
  530. if clamped is not text_obj:
  531. block = dict(block)
  532. block["text"] = clamped
  533. elif not has_body:
  534. continue
  535. elif btype == "header":
  536. text_obj = block.get("text")
  537. if not isinstance(text_obj, dict) or not (text_obj.get("text") or "").strip():
  538. continue
  539. clamped = _clamp_text_obj(text_obj, MAX_HEADER_TEXT)
  540. if clamped is not text_obj:
  541. block = dict(block)
  542. block["text"] = clamped
  543. elif btype == "context":
  544. elements = block.get("elements") or []
  545. if not elements:
  546. continue
  547. clamped_els = [
  548. _clamp_text_obj(el, MAX_SECTION_TEXT)
  549. if isinstance(el, dict) and el.get("type") in ("mrkdwn", "plain_text")
  550. else el
  551. for el in elements]
  552. if any(c is not e for c, e in zip(clamped_els, elements)):
  553. block = dict(block)
  554. block["elements"] = clamped_els
  555. elif btype in ("rich_text", "actions", "context_actions"):
  556. if not block.get("elements"):
  557. continue
  558. elif btype == "table":
  559. if not block.get("rows"):
  560. continue
  561. settings = block.get("column_settings")
  562. if isinstance(settings, list) and any(not isinstance(cs, dict) for cs in settings):
  563. fixed = [cs if isinstance(cs, dict) else {} for cs in settings]
  564. while fixed and not fixed[-1]:
  565. fixed.pop()
  566. block = dict(block)
  567. if fixed:
  568. block["column_settings"] = fixed
  569. else:
  570. block.pop("column_settings", None)
  571. out.append(block)
  572. if not out:
  573. return None
  574. return out[:MAX_BLOCKS]
  575. except Exception:
  576. # A sanitizer bug must never take down the send path.
  577. return None