Skip to content

feat(telegram): emit Bot API 10.2 rich message blocks - #107986

Merged
obviyus merged 5 commits into
mainfrom
feat/telegram-rich-blocks
Jul 15, 2026
Merged

obviyus merged 5 commits into
mainfrom
feat/telegram-rich-blocks

Conversation

@obviyus

@obviyus obviyus commented Jul 15, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Telegram rich messages (channels.telegram.richMessages) were rendered by serializing agent markdown into a Telegram-specific rich-HTML string: a tag allowlist with per-tag attribute regexes, a nesting cap of 16, <br> materialization (Bot API HTML mode drops bare newlines), an HTML tag-rebalancing chunker, and a ~500-line HTML table renderer with ASCII fallbacks. Every one of those layers existed only to survive an HTML round trip that Telegram immediately parses back into blocks, and each was a standing source of can't parse entities 400s and formatting degradations.

Bot API 10.2 added InputRichMessage.blocks, a typed block/RichText tree, which lets the plugin emit exactly what the wire wants — and lets the full agent authoring contract (<details>, checkbox lists, tables with spans, math, media, maps) map to real typed blocks instead of sanitized HTML.

Why This Change Was Made

Four commits:

  1. Test-only: removes the rich-HTML formatter tests superseded by the blocks emitter (split out for the review bundler; see Evidence).

  2. Blocks emitter: markdown → shared markdown IR → typed InputRichBlock[] (rich-blocks.ts), sent via sendRichMessage {blocks} / editMessageText {rich_message: {blocks}} from both funnels. The rich-HTML emitter, sanitizer, nesting limiter, <br> materialization, and HTML table renderer are deleted. The legacy parse_mode: "HTML" path (default when rich is off) is unchanged, and caller-authored HTML (formatting.parseMode: "HTML") stays on that legacy funnel even for rich accounts — parse_mode HTML preserves literal newlines and tag-aware chunking, the contract HTML callers authored against. Structural nesting is recursive (fence-in-quote = pre inside blockquote); plain-text fallback is projected from the emitted blocks so tables/captions/media URLs survive rich-send failures; 500-block/32k-char/50-media limits are enforced by surrogate-safe, wrapper-preserving splitting; skip_entity_detection is document-scoped because the render commits to one linkify decision.

  3. HTML-island layer (rich-blocks-html.ts) + system-prompt update: the agent prompt has always instructed models to author rich content as markdown plus HTML islands (<details><summary>, <ul> + checkbox <input>s, <table> with caption/colspan/rowspan/align, <figure>/<img>/<video>/<audio> (+gif→animation, ogg/opus→voice note), <tg-math>/<tg-math-block>, <tg-map>, <tg-collage>/<tg-slideshow>, <aside>, anchors + fragment anchor_links, sup/sub/mark/tg-spoiler/tg-emoji). This layer parses those islands and maps every advertised construct to its typed 10.2 block, with a strict no-silent-loss policy: malformed, unclosed, stray-content, duplicate-caption, or mixed-validity islands stay literal text rather than partially converting. The "Telegram rich ON" prompt line is rewritten for 10.2 with complete, parseable syntax examples.

  4. Message-tool sanitize fix (pre-existing bug exposed by live E2E): the Telegram outbound adapter ran every message-tool send (visibleReplies: "automatic" groups, proactive sends) through sanitizeForPlainText, stripping the agent's rich islands before the emitter could map them — the streamed preview rendered perfectly, then got superseded by a flattened durable final. The adapter sanitize is now effective-account-aware (the sanitizeText adapter callback gains optional cfg/accountId, wired in deliver.ts): rich accounts strip only assistant-visible scaffolding; non-rich accounts keep the exact old plain conversion. The island matcher also learned to ignore tag names quoted inside <code> elements (live model output mentions tags in prose, which was miscounting match depth).

Error-driven degradation over speculative pre-validation: every structural rejection Telegram can raise (BLOCKS_TOO_MANY, DEPTH_INVALID, TEXT_TOO_LONG, MEDIA_TOO_MANY, TABLE_COLS_TOO_MANY, all RICH_MESSAGE_*_INVALID, can't parse InputRichBlock) triggers the shared plain-text fallback on both funnels — all strings live-verified.

User Impact

Rich-enabled accounts get the full advertised formatting surface rendered natively and reliably: collapsible tool output, native tables (spans/captions/alignment), task-list checkboxes, math, inline media/collages/maps, preserved line breaks, file refs as code instead of spurious previews, and graceful plain-text degradation that no longer drops tables, captions, or media URLs. The default (non-rich) path is unchanged.

Evidence

  • Live Bot API probes (real bot, test group, 2026-07-14/15, ~20 probes):
    • The full island surface accepted in one sendRichMessage {blocks} call and echoed structurally intact: details (open), checkbox list, math block + inline math, sub/sup/marked, divider, captioned photo, map, pullquote; editMessageText {rich_message:{blocks}}, anchor_link, and skip_entity_detection accepted; bare \n preserved in paragraph RichText (unlike HTML mode); README.md stayed code with no server re-linkification.
    • Structural limits mapped empirically: 501 top-level blocks / 17-deep nesting / 40k text / 51 media / 21 table columns → typed RICH_MESSAGE_* rejections (now classified); a 501-row table, 501-child blockquote, 501-item list, and 51 maps are all accepted — only top-level blocks count toward 500 and maps don't consume the media budget, so the splitter counts exactly that.
    • Media/emoji contracts: ogg-as-audio rejected (AUDIO_INVALID) → ogg/opus map to voice notes; gif accepted as animation; unknown-but-numeric custom-emoji IDs accepted (degrade server-side) while non-numeric IDs 400 → validated locally.
  • Blacksmith Testbox (Linux, Node 24): pnpm test extensions/telegram 149 files / 2,808 tests, prompt snapshots, and system-prompt tests green at the final SHA; src/agents suite (628 files / 11,801 tests) green.
  • pnpm tsgo:extensions, pnpm check:test-types, oxlint, oxfmt all clean.
  • Live end-to-end agent turns (real Claude via claude-cli through a real gateway from this branch, rich-enabled group, visibleReplies: "automatic"): the final visible Telegram message renders native details + table + mathematical_expression + checkbox list blocks, confirmed via the Bot API echo. Before the sanitize fix, the same run delivered a flattened final (islands stripped) while the deleted preview had been perfect.
  • Structured autoreview (Codex gpt-5.6-sol, high): 18 cycles across the feature commits, converging to a final clean verdict ("patch is correct — no actionable defects"). ~35 findings fixed along the way (nested-structure emission, fallback content loss, splitting/limits, island parsing edge cases); a handful rejected with live-API counterexamples (recursive block counting, fragment-link rejection, map media budget) or conscious documented trade-offs (anchor locality across >32k chunks). Every accepted external-behavior claim was settled by probing the production API, not by assumption.
  • Note: the test-only commit is split out because the review bundler fails closed on a deleted fixture line containing a ?token=… URL (secret-scanner false positive on removed content); those deletions were manually line-audited and only cover removed internals.

@openclaw-barnacle openclaw-barnacle Bot added channel: telegram Channel integration: telegram size: XL maintainer Maintainer-authored PR labels Jul 15, 2026
@obviyus obviyus self-assigned this Jul 15, 2026
@openclaw-barnacle openclaw-barnacle Bot added the agents Agent runtime and tooling label Jul 15, 2026
@obviyus
obviyus force-pushed the feat/telegram-rich-blocks branch from 696dcac to 19a11e7 Compare July 15, 2026 07:45
@obviyus
obviyus merged commit 02a5ce6 into main Jul 15, 2026
108 of 112 checks passed
@obviyus
obviyus deleted the feat/telegram-rich-blocks branch July 15, 2026 09:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling channel: telegram Channel integration: telegram maintainer Maintainer-authored PR size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant