The Nous provider accepted a Portal token for this agent without a scope
claim as a dashboard sign-in, with a warning. Every dashboard grant and
every peer pass writes the claim, so such a token was minted for some
other purpose; it now opens neither a dashboard session nor any peer
permission. Two test fixtures that minted Nous tokens without the claim
now carry the dashboard scope the Portal writes.
Raised by kshitijk4poor in review.
Another Hermes agent can now call this agent's API server through the
dashboard with a short-lived pass minted for this one agent, instead of
holding its API_SERVER_KEY.
- /api/peer/<path> and /api/peer/p/<profile>/<path> forward to the gateway
api_server on loopback with the key that listener checks. The key never
leaves the machine and nothing new listens on the network.
- Each path needs a permission the pass carries: agents:message for what
`hermes peer` uses (health, capabilities, sessions and session chat, runs,
run events, stop), agents:control (which includes messaging) for the rest
of the user-facing API. Unlisted paths are never forwarded: cron fire,
platform event intake, RoomLink grants, /health/detailed.
- Passes are checked through a new provider capability (supports_peer_pass /
verify_peer_pass), kept apart from verify_token, so a pass never authorises
another provider's token routes such as /api/gateway/drain.
- The Nous provider no longer opens a dashboard session for a token whose
scope lacks agent_dashboard:access. It did not look at scope before, which
was safe only while every token minted for an agent granted the dashboard.
A token with no scope claim is still accepted, like the other contract
claims.
- Control actions are written to the dashboard-auth audit log (peer_control)
with the pass holder, and the api_server records the holder as
peer_principal in a job's origin, so jobs outlive passes attributably.
- /p/<profile>/ reads as the api_server reads it: hermes is the default
profile unless a profile has that name, and an unknown profile gets the
api_server's own 404 body, which `hermes peer` recognises.
- X-Hermes-Session-Key (the api_server's memory scope) passes only with
agents:control. The api_server's replay and partial-turn response headers
come back.
- A gateway that is asleep answers 503 with Retry-After; a request it dropped
after receiving it answers 502 with no retry hint, since it may have run.
Neither counts toward the dashboard's own health.
- The cron-fire listener lookup is split out so the peer route resolves the
same listener, with the key the gateway loads (a usable API_SERVER_KEY
over the configured key).
Review of #152454 (head c71b972bc325), two P2 findings:
- Settling a partial owed edit discarded the unseen tail of an oversized
progress item. A /verbose terminal block is ONE queue item of any length,
so _split_progress_groups could not keep a group under the cap and the
adapter split the owed edit itself; a flood-refused continuation then
settled the owed bubble with 99/180 lines never shown.
- The carried-send retry replayed already-delivered chunks: a carried
remainder holding such an item went out as one send the adapter split,
and a failed continuation made the owed_fresh retry re-send the whole
group (74 lines shown twice).
_split_progress_groups now cuts an over-cap item into cap-sized pieces
(fences closed/reopened), so every group fits one message. A split the
adapter still reports partial (MarkdownV2 escaping can inflate a cap-sized
group) is settled, never retried whole: the certain-undelivered tail the
adapter reports (raw_response["undelivered_chunks"]) is held as its own
obligation, resent via _resume_partial_send ahead of newer lines, and an
uncertain tail is not resent. Telegram's edit-overflow split now reports
that tail on a flood refusal, and a flood refusal of the no-anchor retry
returns the flood result instead of losing the wait.
Inside a flood window the progress overflow roll returns early, so a held bubble near
the cap keeps absorbing lines. A content reset then owed the whole buffer as one edit;
after the window Telegram's _edit_overflow_split re-edited chunk 1 and re-posted every
continuation that had already landed, on every idle tick, and a flood-refused
continuation came back as overflow_continuation_failed with no retry_after, so no
window was armed and the loop never ended.
- _reset_progress_bubble owes the closed bubble one cap-sized group and carries the
rest into the next bubble, where the gateway's own roll sends it and stops at the
first flood refusal (BearHuddleston's patch on #151083).
- _deliver_flood_pending_progress settles an owed edit whose result is a partial
split: its head is on screen, so a replay can only duplicate it.
- Telegram's overflow continuation reports a flood refusal as the flood-cap result
(no MarkdownV2 -> plain retry into the penalty) and _edit_overflow_split forwards
its wait, so the caller arms the window.
Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
Interim stream edits went out as plain text and the finalize edit switched
the same message to parse_mode=MarkdownV2. Telegram clients then drew the
old layout over the new text until a refresh. Previews now use the
formatter and parse mode the final uses. A preview Telegram rejects with
"can't parse entities" is re-edited once as the raw text, so nothing is
lost. The flood-wait retry re-edits in the same mode. rich_messages stays
opt-in and no fresh final message is sent.
Fixes#49536
Slate review P2 (root-lobby filtering silently truncates client-split commands): a >4096-char
root-DM command arrives as a near-limit COMMAND chunk plus TEXT continuations. _handle_command
admits and buffers the command, but the ignore_root_dm gate dropped the continuations, so the
command ran truncated. _handle_command now tags the buffered event with its lobby owner
(chat, sender); the gate admits a root text chunk only while that owner's batch is still pending
with a near-limit last chunk. Genuinely new root chatter stays dropped.
Telegram Android sends the opener of a topic created from "All messages"
without message_thread_id. The ignore_root_dm gate ran before
_build_message_event adopted the created topic, so it dropped the opener as
root-DM chatter. The gate now asks _admit_topic_follow (the per-message,
arrival-ordered decision) and only drops messages that adopt no topic.
The silent-cron typing test spies on send_typing: main's per-chat typing
gate (telegram_typing_gate) now paces the raw sendChatAction across sends.
The ignore_root_dm lobby (c931dad1d9) was dropped from _should_process_message by the
ab48dccf97 god-method split, so the documented key silently did nothing and every
root-DM message from a dm_topics user reached the agent. Restore the gate in the topic
routing sibling (commands, topic messages and chats without dm_topics still pass).
telegram.pretty_tables never had a reader; remove the doc sentence promising it.
Cron deliveries carry metadata job_id and notify=cron.delivery.notify. With
cron.delivery.notify: false the notify guard in _retrigger_typing did not fire, so
the adapter re-armed Telegram's ~5s typing timer after a message no typing loop owns,
and the bubble lingered after the scheduled message landed. A job_id send is
final like a notify send: skip the re-arm for both, on the rich and MarkdownV2 paths.
Salvages #50792 (job_id guard), ported onto the current _retrigger_typing.
Co-authored-by: Gurud25 <198068347+Gurud25@users.noreply.github.com>
window on every new generation, not only on a 409. On a link that drops
the long poll more often than every 120 s the window never closed, so
isolated 409s hours apart accumulated on one ladder and the sixth went
fatal.
A new generation now pauses the window instead: healthy polling proven so
far stays banked and only the downtime before the next progress is
excluded. Only a 409 empties the bank, so a live storm still climbs. The
window bookkeeping moves into the telegram_polling_probe sibling so the
adapter does not grow.
A 409 "terminated by other getUpdates request" conflict is contention for
the single-writer polling slot — a zombie getUpdates session from the
previous gateway process, or another instance holding the token — not a
permanent configuration error.
The adapter already retries the conflict internally (MAX_CONFLICT_RETRIES=5,
200s total, drop_pending_updates=True to terminate the competing session).
Once that budget is exhausted it marked the error retryable=False, which
dropped the platform with no path back:
- GatewayRunner._queue_retryable_fatal_platform returns False when
adapter.fatal_error_retryable is false, so telegram never entered the
reconnect queue.
- The stranded-platform check in
_handle_adapter_fatal_error_detached is also gated on
fatal_error_retryable, so it did not fire either.
Net effect: the gateway stayed up serving its other platforms with telegram
pinned in the "fatal" state indefinitely. Nothing retried it, and the
process never exited for the service manager to restart it.
Observed on a real deployment: a rapid restart chain (three gateway
processes inside four minutes) left a stale getUpdates session on Telegram's
side. The incoming gateway burned its five retries, then telegram was dead
for 31 minutes until a manual restart — even though a raw getUpdates
returned {"ok":true,"result":[]} long before that point.
Marking the error retryable=True routes it through the existing reconnect
watcher: exponential backoff (30s, 60s, ... capped at 300s) with a fresh
adapter on every attempt, reconnecting automatically as soon as the
competing session expires. The existing reconnect_attention_after
escalation still makes a permanently broken loop loud, so a genuine
two-instance conflict does not stay silent.
The stranded-platform net keeps its retryable gate: that gate is correct.
Genuinely terminal failures (missing_credentials, telegram_auth_error,
relay_disabled) must not exit the whole gateway.
Test: tests/gateway/test_telegram_conflict.py asserts fatal_error_retryable
is True once the retry budget is exhausted, pinning the classification.
Cron's standalone send cap (cron.standalone_send_timeout_seconds, 60s) and the
live-adapter per-attachment cap (cron.media_send_timeout_seconds) now widen by
1.5x the files' upload time at 128 KB/s, as the Telegram gateway deadline does.
The size math moves to gateway.platforms.helpers (media_upload_seconds,
scaled_upload_deadline) so cron and the Telegram plugin share it without a
core->plugin import. Text-only sends keep the configured value. Docs describe
each path's real bound.
Review finding: cron standalone delivery still has a fixed 60s wall-clock cap;
doc wrong (P2).
A Bot API server answers sendDocument/sendVideo only after the whole body has
reached Telegram and been processed. The gateway used a fixed 60s read budget
and a 300s wall-clock deadline regardless of size, and the standalone sender
(hermes send, cron, agent send_message) used the Bot's 20s general read
timeout. Large files on slow uplinks or a self-hosted Bot API server, and
small files Telegram takes a while to process, came back "Timed out" and
then landed anyway; a retry duplicated them.
telegram_media_budget.scaled_budgets adds the on-disk payload's transfer time
at 128 KB/s to the read and write timeouts and 1.5x of it to the deadline
(capped at 1h); URLs, file ids and in-memory bytes keep the fixed budgets.
The gateway's _send_media, the album chunk sender and the standalone upload
all use it. A standalone timeout warning now says Telegram may still deliver
the file, and plain `hermes send` prints the result's warnings so the cause
is visible next to the generic "No deliverable" error.
Fixes#133093, fixes#133164, fixes#117795.
Co-authored-by: liuhao1024 <sunsky.lau@gmail.com>
Round-4 review finding (resolve_routing / merge_batched_event): an item routed to
'no topic' on arrival split its burst or album. Photo 1 arrives before any binding
and is pinned unbound; photo 2 recovers to topic 10 and opened the <key>|<topic>
lane, while dispatch recovered photo 1 into topic 10 too: two turns in one topic.
A pending base-lane batch whose arrival routing found no topic is routed again
when a later item would split from it; if it now resolves to the same topic, they
merge. A recovered or adopted route still keeps its arrival topic, so events
routed to different topics never share a batch.
Review round 3 (#151809): after a routed split, an unpinned photo merged
into the first lane, so the second question's second photo ran in the
first question's topic.
Invariant: every event in one batch has the same resolved session key.
Each photo or album item is routed (topic recovery) when it arrives, before
it may join a batch, and merge_batched_event places it only in a lane of
that route: the base lane when it is free or already on that route, else
'<key>|<route>'. Recovery at flush no longer re-derives an older item's
topic from a binding made later.
Property test: 10 two-step grid shapes (burst/new album/same album, with
and without a rebind) plus 8 seeded 3-step sequences at the production
0.8 s window, asserting topic per event, no image lost or duplicated, and
question+photos one turn when routing holds.
Round-2 review P2: two question+photo pairs within one 0.8 s photo-burst
window, with a different topic bound between them, merged into one turn in
the first pair's topic (main: topics 10 and 20). The burst key is taken
before absorption, so both pinned photos landed in one lobby-shaped lane and
merge_batched_event folded the second in under the first's routing.
merge_batched_event now compares the resolved session key of two pinned
events and, when they differ, moves the later one to its own lane keyed by
its routing (photo bursts and albums alike; an album lane split this way
still waits for its in-flight siblings). Unpinned merges are unchanged.
Slate review P2 (absorbing text discards its recovered topic): absorb_claimed_text checked the
lane on a disposable recovered copy, then dispatched the unrecovered photo event, so a DM-topic
binding that changed during the photo debounce moved the question from topic 10 to topic 20.
The photo now adopts the lane already resolved for the question (source with its pinned identity,
topic skill and channel prompt) through one helper, telegram_batching.adopt_routing; the album
merge carries that pinned routing onto the album's seed event, and the photo-burst key is taken
before absorption so the burst lane is unchanged.
The claim now runs inside the media handler after the group gate and
attribution (still before its first await), keyed on the image's own event. An
observe-only photo returns before that point, so the question flushes on time
instead of waiting up to 8s for a download that never joins it.
Review finding: observed photos delay answers (Greptile P2).
The image claims only the pending text batch under the key its own text would
batch under (topic recovery and observed-group sender included). Before, a
photo in topic B claimed the user's question in topic A: they never merged, but
the question waited on the photo's download (up to 8s).
Review finding: cross-topic photo claim delays the question (P2).
The claim matched only source.user_id, which observed groups clear (the sender rides on the
event: MessageEvent.sender_id), took the first pending text in the chat regardless of topic,
and missed image documents identified only by filename. is_image_document is now shared with
_cache_inbound_document so the two cannot drift.
A short text flushed after its 0.18 s quiet period while the photo sent
right after it was still downloading and then sat in its own 0.8 s burst
batch, so the agent answered the question without the image and got the
image as a second turn.
Updates of one chat run in order, so when the image handler starts, the
text it belongs with is still pending. The handler now claims a pending
text-only batch from the same sender in the same chat before its first
await. A claimed text flush waits (after its normal delay, at most 8 s)
for that handler, and the image absorbs the text when it reaches the
photo batcher, only when both land in the same session/topic lane. A
lone text keeps its latency; a photo sent after the text flushed stays
its own turn; another sender's photo never takes the text.
New sibling plugins/platforms/telegram/telegram_text_photo_pairing.py;
adapter.py stays at 6,922 lines.
Idea credit: #105050 (claim the pending comment at media admission, wait
in the text flush) -- reimplemented narrowly, not ported.
Co-authored-by: Mene <mene-crab@proton.me>
Independent review of 253bf6d9727 (blocking): the typed-text values this
PR records lived in event.metadata, and native admission refuses any
metadata key outside its WhatsApp allowlist, so a Telegram reply carrying
one was dropped with "Hermes refused this message (invalid_params)".
253bf6d9727 widened that from voice-note replies to every reply.
Both values now ride private event attributes (_telegram_typed_text,
_telegram_replied_voice_typed_text), as the album item notes already do,
and never reach the envelope. The batch keeps its typed text on every
merge, not only once a voice-note reply is in it, so three-chunk merges
with the voice reply last ([photo, plain, voice], [plain, photo, voice])
also answer a clarify with typed text only (review should-fix).
The tests assert the merged event clears native admission's metadata
check, across voice/photo/plain orders of two and three chunks.
Review P3 on ff548e7d5d2: when one merged text chunk replied to a voice
note and another replied to a photo or document, the photo's
"[Replied-to image ... saved at: ...]" note joined the clarify answer,
because merged_replied_voice_typed_text took any chunk without the voice
key as all typed text.
cache_replied_media now records each replying chunk's text as
typed_text before any replied-to note is appended, and the merge uses it.
The agent still sees every note; only the clarify answer is typed text.
Review P2 (typed reply text captured before the text-chunk merge): the
separately stored replied_voice_typed_text came from one chunk, so a
voice-note reply 'option B' plus the continuation 'and keep the logs'
answered a pending clarify with 'option B' only. The Telegram enqueue now
recomputes it over the merged chunks (attachment note still excluded);
this also covers plain text first, voice-note reply second.
The replied-voice shortcut in _prepare_clarify_reply_text returned event.text, which by
then carried the replied-to attachment note, so typing "2" while replying to a voice
note reached the choice matcher as "2\n\n[Replied-to ...]" and cancelled the question.
It also skipped STT for every captioned TEXT event, including a sender's own audio with a
caption (Google Chat keeps TEXT for that). The Telegram adapter now records the typed
text in event.metadata["replied_voice_typed_text"] only when it attaches a person's
replied voice note; the clarify path answers with exactly that, else transcribes as before.
A typed reply to a person's voice note was retyped AUDIO by _attach_cached, which the
gateway treats as a file and never transcribes; it now keeps the reply's type (the bot's
own voice note and replied audio files still are not transcribed), and a typed reply stays
the clarify answer. A replied-to attachment that is oversized, failed or unreadable now
appends a note like the observed-media path instead of vanishing.
Fixes#137333, fixes#122617.
Salvages #95740 (@djagya).
Every inbound get_file()+download site (photo, voice/audio/video, image/video/generic
document, sticker, observed and replied-to media) was single-attempt, so one stalled
getFile read (PTB TimedOut) lost the attachment. The fetch is a pure read, so it now
retries as one unit (2s, 5s) on transport errors; BadRequest/auth/pool timeouts stay final.
The helper lives in telegram_media_fetch.py (adapter.py shrinks).
Fixes#150861, fixes#47093.
Salvages #150862 (@zeta92); supersedes #47160 (@Pluviobyte).
Co-authored-by: Pluviobyte <Pluviobyte@users.noreply.github.com>
Review round on #151769:
- validate_media_delivery_path is a pure path check again; the Docker handback
runs after filtering via asyncio.to_thread (profile scope carried by
contextvars) on the reply, post-stream and /background delivery paths.
- hand_back_media_file returns False on any docker/record failure instead of
raising out of reply extraction.
- observed_media_note appends its guidance after the full context_note; the
video hint names video_analyze only when available (opt-in toolset).
- handback test skips as root; new tests for off-loop and failure paths.
An unmentioned group photo is cached and only a text note reaches the shared
observed context, which is text-only by design. The note named the path but
not that the image was never attached, so on the next @mention the agent
asked users to re-send. The observed note now says the file is not attached
inline and names the tool to open it (vision_analyze / video_analyze), so
image tokens are spent only when someone asks.
CI's boundary lint failed: the new adapter_image_batch.py imported
gateway.platforms.base_log_safety.safe_url_for_log, a core name outside
the published plugin API, which adapter.py already imports under its
baselined crossing. The helper now receives it from the adapter like its
other collaborators, so moving the code adds no new core crossing.
- Slack/Mattermost send_multiple_images and Weixin send_image send a refused
(unsafe, failed or over gateway.max_inbound_media_bytes) remote image's URL
and caption as text instead of dropping it; the URL already left the reply
text. Slack's batch download moves to adapter_image_batch.py.
- _dedupe_audio_paths groups by size first and hashes only repeated-size
groups once each.
- The cap test proves the download stops near the cap (server-side byte
count), and the Telegram flood test stubs the streaming client.
Image URLs in an agent reply are downloaded by Slack / Telegram / Feishu /
Mattermost / Weixin before upload, and those paths read the whole body into
memory with no cap, so a streamed unbounded body could OOM the gateway.
They now stream through the same capped reader the inbound path uses and
take the adapter's existing fallback when the cap is exceeded.
Rebased onto current main (adapters moved under plugins/platforms/, the
SSRF redirect guard went public as ssrf_redirect_guard). The capped reader
is made public too (read_httpx_body_with_limit) so the plugins do not add
new private-core imports; the Teams baseline entry for the old private
name is dropped.
Fixes#122667
Review of #152385 (P2): the `hermes pause` gate let every message through
while an /update prompt was pending, because on main any message there
was swallowed as the update answer. With the prompt now bound to its
opener, another member's message is an ordinary turn, so it slipped past
the pause and started an agent run. The pause bypass now applies only to
a reply the prompt would actually accept (the opener or a chat admin);
both checks share one helper.
Also from that review (P3): the Discord update view is recognised by an
explicit attribute rather than its class name, and the duplicate
_authority_refusal definition in approval_actor is gone (the remaining
one is the stricter, dict-checking copy that was already in effect).
A picker card (/model, /reasoning, /fast, the usage-limit switch offer)
and the /update Yes/No prompt only checked the chat allowlist on a tap,
and a pending /update prompt took the next message ANY admitted member
sent in the session as its answer. In a shared group with
group_allow_admin_from set, a member refused /reasoning or /model could
tap the admin's open card and apply it, and anyone's chat text answered
the admin's "Restore local changes now?".
The gateway now records the opener (sender id, name, chat scope) when it
sends the card (prompt_authority on the selection callback) and in the
/update pending marker. Every renderer refuses another member's tap with
the existing localized "Only <name> can answer this approval." note and
leaves the card open: Telegram mp:/cp:/update_prompt:, Discord
ModelPickerView/ChoicePickerView/UpdatePromptView (one _gate), Slack
model picker (ephemeral), Matrix picker reactions, Feishu choice picker
and update card (toast). A non-opener's typed text during a pending
/update prompt falls through as an ordinary message. The check is
gateway.approval_actor.may_answer, the same rule exec approvals use:
the opener and the chat scope's admins always pass; a sender-less card
(shared observed route) keeps the old anyone-admitted behaviour.
QQBot's update button already accepts only the session's own user.
picker_refusal / update_prompt_refusal join approval_refusal in the
published plugin API so platform plugins can apply the same check.
With `allow_admin_from` set and the default `approvals.approvers: ["*"]`, a non-admin was
refused `/approve` but could still answer an admin's blocked command by typing a bare
`always` (which also writes the profile-wide allowlist), tapping Allow on any adapter, or
answering a `/reset`-style slash confirm.
`gateway.approval_actor.may_answer` now takes the answer's command (`approve` / `deny`, or
the confirmed command) and the chat's full slash policy, so one decision covers every path
main already routes through it: `/approve` and bare words, typed confirm replies, relay,
and the Telegram/Discord/Slack/Matrix/Feishu/Teams/WhatsApp Cloud buttons; QQ Bot's settle
now passes the clicker too. Precedence: a narrowed `approvers` decides on its own
(requester, listed ids, admins); under `["*"]` the slash policy decides (admins plus
`user_allowed_commands`). No admin list, admins and clarify answers behave as on main.
Fixes#120506
Co-authored-by: Froraut <79215537+Froraut@users.noreply.github.com>
Co-authored-by: John Paul Soliva <soliva.johnpaul@icloud.com>
Review blocker on #151930 (data loss): only `_send_fallback_final` read the adapter's
`raw_response["unattempted_chunks"]`. The first send (`_first_send` ->
`_hold_ambiguous_first_send`), `_try_fresh_final` and `_send_empty_fallback_final` treated any
timed-out send as fully shown. When Telegram's legacy MarkdownV2 path re-split the content
(e.g. 3,000 periods escape to 4,088 + 1,928 chars) and the first message timed out, the turn was
reported delivered and the second message was never sent.
All four sites now ask one predicate, `_uncertain_send_fully_shown`: a send that may have landed
counts as shown only once nothing is left unattempted. When messages are left, only those are
sent, through the adapter's `_resume_partial_send` (now also fed by `unattempted_chunks`, which
carries the formatted chunks instead of a count). The possibly-landed message is never sent
again. When the rest cannot be sent, the send counts as undelivered and the gateway's own final
send runs: a repeated head is better than a lost tail.
Greptile thread 4515251115: the fallback guard guessed the send path from
format_message(chunk) length, so a continuation whose MarkdownV2 form exceeds
4096 but that went out as ONE sendRichMessage (landed, then timed out) was
rejected, the turn stayed unconfirmed, and the gateway resent the whole answer.
The Telegram adapter now reports the fact instead: an uncertain send failure
carries raw_response["unattempted_chunks"] when messages after the one in
flight never left (legacy MarkdownV2 re-split). The rich path has no further
messages and reports none. The consumer counts a may-have-delivered chunk as
shown unless the adapter reports unattempted text; adapters that report
nothing (one send per call) keep the counted-as-shown behaviour.
_fits_one_platform_message is removed. adapter.py does not grow.
_query_doh_provider called client.get(...).json(), so the whole body was
buffered whatever its size. A captive portal, proxy or broken DoH endpoint
answering with 64 MiB pushed peak allocation to 208 MB during adapter connect.
The provider is now read as a raw stream with Accept-Encoding: identity, so
compression cannot inflate it past the cap. A body over 64 KiB marks that
provider as failed, the same as any other DoH error, and the other provider's
answer is still used. Real Google and Cloudflare answers are unchanged.
Supersedes #55089 (@ooiuuii) with a smaller in-module read (no new shared helper).
An unmentioned dice throw in an observed group was saved by _gate_or_observe
before the dice text existed, so the transcript held only the sender header.
Build the dice event first and hand it to _observe_unmentioned_group_message,
the same shape the contact card uses.
test_unserved_update_not_receipted_and_logs_field_names used a dice message as
its example of an update no core handler serves; dice are served now, so it
uses a new_chat_title service message (stable across Bot API versions, unlike
poll payloads).
Fixes#78719.
A Telegram dice message (🎲🎯🏀⚽🎳🎰) carries no text or media, so it
matched none of the adapter's handler filters and PTB dropped it with no
log. Register `filters.Dice.ALL` and turn the throw into a text event
("[The user sent a Telegram dice: 🎲 rolled 4.]") through the same
authorization and group gate/observe path a location pin uses. The handler
lives in a sibling module (`telegram_dice.py`) since the adapter is far
past the file-size cap.
`test_media_handler_accepts_video_notes` stubs PTB's filter namespace with
a fixed set of names; the stub gains `Dice` so the registration call
resolves (its assertion is unchanged).
Also the Telegram half of openclaw/openclaw#137112 (flagged by the openclaw
scout 2026-10-18).
- Telegram stop_inbound sets the polling fence even when the updater is stopped
(conflict/network recovery sleeping between stop and restart can no longer
restart polling after the handler is withdrawn).
- Slack stop_inbound closes the socket under _socket_reconnect_lock, so a
reconnect already past its _running check finishes first and its replacement
socket is the one closed.
- drain_gateway_runtime stops every adapter's inbound concurrently under one
INBOUND_STOP_SECONDS bound, leaving the settle phase its leash.
drain_gateway_runtime set every adapter's handler to None while Telegram's
getUpdates long-poll and Slack's Socket Mode kept receiving: each update they
acked in the drain window hit handle_message's handler-less drop and was never
redelivered (live: a DM sent during a SIGTERM drain was logged as dropped and
never answered, even after the reboot).
The drain now calls an optional adapter seam, stop_inbound(), first (every
profile's adapters; a failure logs and the disconnect retries it). Telegram
stops the updater and fences the polling lifecycle so the reconnect ladder
reads it as teardown; Slack closes Socket Mode with _running=False so the
watchdog cannot reconnect. Egress stays up for admitted work. Unfetched
updates stay on the platform and are answered after the restart.
Telegram's method lives in telegram_held_inbound.py; Slack's in a new
adapter_socket_lifecycle.py mixin (with _cancel_socket_watchdog moved out) so
neither over-cap adapter grows.
Fixes#143122
Co-authored-by: liuhao1024 <liuhao1024@users.noreply.github.com>
Round-4 review: since the $ escape runs per prose stretch between code regions
(78a87c7c), a prose "Use $$ to get the shell PID." paired with a later display
formula's $$ across a code span, so the amounts in between ("Cost is $5 vs $10")
were left bare and rendered as garbled math, and the real formula's $$ was left
unpaired (6 of 20k corpus replies). A $$ pair now stays in one prose stretch: its
body holds no backtick, blank line, or bare $ before a digit (an amount).
A fence opens at a line start (CommonMark). The lead-in fence shape
("Here is the code: ```bash") now counts only when the run ends the line and
a later fence line closes it; "Use ``` to open a fence. Cost is $5" kept the
rest of the reply as code and lost main's \\$ escape. A line-start fence still
streaming unclosed stays code (#151725).
Review of b0d95849a029 (P2, quadratic prefix copy): _resolve_emphasis
measured the backslashes before each star run with
text[:run_start].rstrip('\\'), copying the whole message prefix per star.
A message of escaped stars ("\* " repeated) went quadratic:
to_markdown_v2 on 524 KB took 1.79 s (main 0.34 s), _resolve_emphasis on
1 MB 10.8 s (main 0.60 s). TelegramAdapter.send formats the whole content
before truncate_message, so the 4096-character chunk cap does not bound it.
Walk back over only the contiguous backslash run instead: 0.10 s / 0.06 s.
A differential fuzz of 20k random star/backslash/space/backtick strings
gives identical to_markdown_v2 and _resolve_emphasis output to the old head.
#151722: `**rm -rf *.tmp**` came out as `\*_rm \-rf \.tmp_`: the `*` of
`*.tmp` (it can both open and close) closed one star of the `**` opener, so
bold turned italic and the star vanished. Pairing now applies CommonMark's
rule of 3, and a bare `**` closer reaches past single-star openers to the
`**` opener (chat text means bold around a literal star; CommonMark's nested
italics would drop it). Backslash-escaped stars (`**Use \*args**`) are
literal. Failed searches remember their floor per closer class, so pairing
stays linear.
#151725: the rich-message `$` escape found code with a backreference regex
that rescanned to end of line from every unmatched backtick run (32 KB in
~2-5 s on the event loop) and knew only closed ``` fences and one-line spans,
so it put `\$` inside a streaming (unclosed) fence, ~~~ fences, indented code,
nested fences and <code>. New rich_code_regions.py finds code in one pass
(block fences incl. unclosed-to-end, indented blocks, width-matched backtick
spans by bisect, <pre>/<code>); the escape and the link degrade run only on
the prose between. standalone's HTML-tag sniff uses the same scan. A TeX
command's {...} argument may hold words, so `$1\text{ kg}$` stays math.
Fixes#151722Fixes#151725
`_crosses_quote_edge` located the enclosing line with an unconditional
`text.rfind("\n", 0, start)` before it even looked for newlines inside the
span, so every Markdown link on a long single line re-walked the whole
prefix: quadratic in the link count, and a regression against main, whose
predicate only located the line when a newline actually matched.
Answer "no newline, no crossing" first, then walk newlines with `str.find`
bounded by the span, so the one-line case never touches the prefix and the
multi-line case no longer copies the span. Helper cost for one line of
short links: 8000 links / 128 KB 9 ms -> 1 ms; 500 links through the
formatter still convert and stay MarkdownV2-valid.
Reported in review by kvnloo, whose fork add-on commit showed the same
guard; the regression here drives the real helper with a str subclass that
raises on `rfind` so it fails on the scan, not on timing.
`format_message` pairs ** and * runs by asking, for every candidate pair,
whether the span between opener and closer contains a newline, a blank line
or a blockquote line edge. Each question sliced `text[o_end:start]` and ran
its own `re.finditer("\n", ...)` (plus an `re.compile` of the quote marker),
so a distant unmatched `**` opener made one reply cost closers x span: 32 KB
took ~1.4 s and 200 KB ~106 s synchronously on the gateway event loop, once
per send and once per streamed edit (#151723).
Precompute the line edges once per `_resolve_emphasis` call - the newline
positions, the `\n\n` starts and the newlines that border a quote line - and
answer all three questions with `bisect`. `_crosses_quote_edge` keeps its
span-wise scan for the link path (one short span per link) and now shares
the same line predicate instead of compiling its regex per call.
Output is unchanged: 4001 differential cases against upstream/main - 2000
random metachar strings, 2000 line-structured strings built to hit all three
predicates true and false, and the issue's 32 KB payload - are
byte-identical. 32 KB formats in ~9 ms and 200 KB in ~61 ms.
Fixes#151723
Round-2 review P2: `\$\$` anywhere outside code opened a math region that
ran to the next `\$\$` across blank lines and fence openers, so a shell answer
("PID is $$ here" + a bash fence with `echo $$`) got `\#!/bin/bash` inside
its code block. Display math now closes only before the next backtick, blank
line or tilde fence opener; otherwise the `$$` is literal text and code
regions keep precedence.
P3: an empty list item followed by a blank line has ended, so a 3-space
fence after it is a top-level fence whose body is code.