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.
Slate review P2 (hash escaping corrupts actual fenced code): a fence closed at
any matching backtick run anywhere in its body, so `text ``` trailing` inside a
block ended it, `\#` landed inside the code and the real closer reopened a fence
that swallowed the following prose ref.
A fence now closes only on a line of its own (opener's char, width >= opener,
only trailing whitespace, <=3 columns past its container) or where its quote /
list item ends; a 4+-column "fence" under prose is not one. Inline code spans
pair only an equal-length run inside the same paragraph (blank line, heading,
list item or fence opener ends it), an unclosed run is skipped whole and an
escaped first tick is literal. The list pass reads fences from the same scan.
Also covers the P3 (`open\n\n#89\nclose` paired across paragraphs). Scan stays
linear: 128 KB adversarial inputs 0.002-0.03 s.
Review P3 (superlinear inline-code regex): `(?P<ticks>`+)(?!`).*?(?P=ticks)`
rescanned to the end of the text for every unclosed backtick run, so a
32 KB rich reply of distinct-length runs blocked the event loop for seconds
on every draft refresh. The regex now only spots a backtick; the closer comes
from an index of backtick runs by length (bisect per run). Differential fuzz
against the previous regex: identical output on 260k random inputs.
Inline ```x``` no longer opens a block fence that swallows the rest of the reply (so a
following #89 is still escaped), the ordered-list separator skips lines inside a multiline
code span, and the email detector only starts at a token boundary so a 40k-char draft no
longer costs seconds (tripped the TeX backtracking budget test).
Moves rich_normalize_linebreaks (+ the ordered-list separator and protected
region regex) and the email-token regex out of the adapter facade into
plugins/platforms/telegram/rich_markdown.py, so the facade shrinks under the
file-size ratchet while _rich_message_payload stays the single seam for
send, edit and draft.
CommonMark only lets an ordered list interrupt a paragraph when it starts
at 1, so '**Label**\n7. item' stayed one paragraph and the numbers reached
Telegram as literal text without list layout. _rich_separate_ordered_lists
inserts one blank line before such a list while leaving list and blockquote
continuations, indented lines, fences (including an unclosed streaming
draft fence) and lists starting at 1 untouched.
Fixes#124552
Google asks integrations to use the Interactions API by default, and new
models and capabilities launch there. With gemini_api unset (auto), the
gemini provider now sends Gemini 3+ models and the gemini-*-latest aliases
to Interactions on the AI Studio host.
Unchanged:
- Gemini 2.x stays on generateContent: it steers thinking with
thinkingBudget, which Interactions has no field for. Gemma stays too.
- Vertex express and proxy bases stay on generateContent (Interactions is
AI Studio only).
- providers.gemini.gemini_api: generate_content (or the per-model form)
restores the previous behavior; it applies on the next request.
Checked against the live API on gemini-3.8-flash and gemini-4-argon:
implicit prompt caching hits the same in stateless Interactions as in
generateContent (27.9K of 30K prompt tokens cached from turn 2 on both).
The generateContent e2e fake speaks only that dialect, so its homes pin
gemini_api: generate_content.
Google's Interactions API is now the recommended Gemini interface and where
new Gemini capabilities launch. The gemini plugin now
supplies its own client (ProviderProfile.create_client), which sends each
call to Interactions or to generateContent per model:
- providers.gemini.gemini_api / providers.gemini.models.<m>.gemini_api:
interactions | generate_content | auto (default). auto keeps
generateContent except for INTERACTIONS_MODELS (empty for now, so
default behavior is unchanged). Only the AI Studio host has Interactions,
so Vertex express and proxy bases stay on generateContent.
- Stateless (store: false): the full history goes as typed steps, so
compaction, branching and model switches behave as on generateContent.
Thought signatures ride extra_content.google.thought_signature (the
existing slot) and replay as thought steps.
- Streaming (step.start/delta/stop, arguments_delta, thought summaries and
signatures), usage (thoughts folded into completion tokens), status to
finish_reason, in-band errors mapped to HTTP-equivalent codes.
- Long decode continues requires_continuation hops with
previous_interaction_id + continuation_token, which needs a stored
interaction, so only those requests set store: true.
- A long-decode stream that drops resumes from its last mid-stream
checkpoint token (same request, continued), as the generateContent path
does. Output past the checkpoint voids it: resuming would repeat that
output, so the turn is retried instead. The dropped hop is counted up to
its checkpoint.
One core line: gemini_api joins the known providers.<name> keys, so setting
it no longer logs "unknown config keys ignored". Otherwise core is
untouched: the generateContent path is the existing GeminiNativeClient,
and the plugin rebuilds the same keepalive client and provider TLS settings
the core gives it.
Review of #152310 (blocking): _hm_clarify_reply checked the sender against the
session's oldest clarify, awaited transcription, then answered whichever clarify
was oldest by then. If Alice's question expired mid-transcription and Bob's turn
asked its own, Alice's transcript answered Bob's question unchecked. The reply now
resolves the checked clarify_id (clarify_gateway.attempt_text_response); if that
entry is gone, the transcript falls through as an ordinary message. Every other
answer path (relay, Telegram/Discord/Slack/WhatsApp Cloud/Feishu taps, typed
slash confirm) already resolves by exact id with no await between check and resolve.
P3s from the same review:
- Feishu HTTP-webhook card replies keep the refusal toast, as long-connection
mode does (a refused tap answered {} before).
- _prompt_refused_to's string dispatch becomes two direct helpers.
- _request_slash_confirm reads event.sender_id(); the decline-fallback test
now passes a real MessageEvent instead of a SimpleNamespace.
Co-authored-by: necoweb3 <65560494+necoweb3@users.noreply.github.com>
#152125 bound shared-chat exec approvals to the requester (or
approvals.approvers / the platform admins), but the other prompts a chat
member can answer for someone else stayed open: another member could press
"Always" on a relay or native /reload-mcp confirmation and run its handler,
or answer the agent's clarify question (a choice button, "Other", or a typed
reply) for the person who asked.
Both prompts now record the same authority an exec approval records when
raised (tools.approval_context.prompt_authority: the turn's actor, else the
command's sender, plus approvals.approvers and the chat type), and every
chat answer path checks it through gateway.approval_actor.may_answer:
- relay prompt_response (gateway/relay/prompt_resolvers.prompt_refusal),
with the bot-owning profile's admins as for exec approvals;
- Telegram, Discord, Slack, WhatsApp Cloud and Feishu button callbacks
(slash_confirm_refusal / clarify_refusal, published on the plugin API
beside approval_refusal);
- the runner's typed-reply intercepts (/always, "2", free text after
"Other"); another member's text is routed as their own message.
A refused tap gets the existing "Only <name> can answer this approval."
and the prompt stays pending. A turn merged from two senders records no
requester, so only approvers and admins can answer, as for approvals.
The default approvers ["*"] keeps today's behaviour.
Supersedes the slash_confirm/clarify half of #72008, whose session-owner
mechanism no longer applies on main (main records the requester itself).
Co-authored-by: necoweb3 <65560494+necoweb3@users.noreply.github.com>
5948ab52e2 made a typing keep-alive take the chat's shared send+edit
slot when it fired. The stream consumer SKIPS an interim edit while that
slot is held, and `_keep_typing` ticks every 2 s with a 1 s slot, so in a
group (which streams by editing one message) typing kept stealing the
slot from the preview edits: the preview stayed on its first chunk. When
Telegram then refused the finalize edit, the continuation was computed
from that stale prefix and the first message read "<<A-fin-stre", so the
answer's opening never appeared whole.
Typing still checks the slot and the flood window (it stays quiet while
a send or edit holds the chat) and still sends at most one call per chat
per 2 s, so #99643's fix (N DM topics multiplying sendChatAction) is
kept. It just no longer claims the slot.
Release-only e2e red on v0.23.1 rc.2 (run 42720042886):
test_telegram_contract.py::test_contract[stream_finalize_rejected_group],
8/8 locally on 4f6ebb9afe. Bisected (DM cell + group cell together, as
CI runs the file) to 5948ab52e2. With this change: the pair passes 3/3
and the whole contract file passes (14/14).
The fallback transport walks sticky -> IPv4 literals -> hostname inside one
send, and every path got the client's full 10s connect timeout. With the two
seed IPs that is 3 x 10s = 30s, exactly the telegram-send deadline. The
deadline fired mid-walk as a bare TimeoutError, which _classify_send_exception
must treat as possibly delivered (retryable=False), so the reply was dropped:
no retry and no plain fallback.
Both transports built by build_ptb_requests now share a 15s connect budget per
request walk. The first path keeps its full connect timeout and later paths
split the rest. The walk therefore ends with its own ConnectTimeout, which is
classified as a safe retry. A tighter configured connect is never widened.
Salvages #136427 (@liuhao1024). The budget split is ported. The adapter.py
hunks (moving _shutdown_abandoned_app) are dropped: the budget now lives in
the shared request builder.
After a replacement reconnect an in-flight turn keeps the retired adapter.
send() already delegated to the replacement, but edit_message() and
delete_message() returned "Not connected"/False, so progress fragmented into
new bubbles and cleanup left them behind. Both now delegate the same way.
The replacement lookup (moved with the reconnect wait into
telegram_replacement.py, shrinking adapter.py) resolves through the
runner's _adapters_for_profile only, so a secondary with no live
replacement fails closed instead of borrowing the primary bot.
_replacement_telegram_adapter() looked the reconnect replacement up in runner.adapters, which only ever holds the PRIMARY profile's map. A torn-down secondary adapter therefore delegated its in-flight sends - mid-turn progress, notices - to the primary profile's bot, delivering one profile's traffic into another bot's chat (#143364, tracker row MSG-43).
Resolve through runner._adapters_for_profile(self._owner_profile) instead: a named profile with no live adapter gets {} and fails closed, the primary keeps its own map. _wait_for_reconnection() shares the helper, so a stale secondary now actually waits for its own reconnect instead of seeing the primary's live bot.
Closes#143364.
DoH routinely answers api.telegram.org with a single A record. The adapter
discovers fallback IPs once per connect, so that lone IP was the whole
fallback path: a DNS blip plus that edge going dark stranded polling until
a restart. The seed IPs now always follow the DoH answers.
Salvages #76685 (@duclucky), re-applied onto the current discovery code.
Review finding (#151772, P1, Greptile 4515985243): the processor and the
adapter kept separate creation records. A slow root DM update held the chat
lane, so the forum_topic_created handler (the adapter's record) ran after
the first explicitly threaded message had already ended the follow, and a
later thread-less root message within five seconds adopted the topic.
Creation and adoption are now one ordered decision: update admission calls
the adapter's _admit_topic_follow in arrival order (recording an authorized,
non-bot creation; adopting, extending or ending the follow), and the
handlers reuse that per-message result instead of deciding again.
Greptile finding "Follow-ups overtake the topic opener": a thread-less DM
opener the adapter adopts into a just-created topic stayed on the chat
queue, while later explicitly-threaded messages used the topic queue, so a
slow opener (photo download) could be overtaken. The update processor now
mirrors the creation record and queues such an opener on both the chat lane
and the new topic's lane.
A message outside allowed_topics was dropped with no log line, so a topic
the operator meant to allow (often a thread-less General message read as
topic 1) looked like a dead gateway (#52635). The first drop per
(chat, topic) is now named at INFO with the allowlist. _topic_gates_pass
moves from adapter.py into the topic-routing mixin.
A plain group reply carries message_thread_id as a reply anchor, and a
forum_topic_created service message must stay ahead of the thread-less
opener that adopts its topic, so both keep the chat lane.
Keep the authorization invariant from teknium1's #152125 when Feishu
combines two admitted members' messages in one text or media batch.
Regression: the shared group approval must have no single requester.
approvals.approvers: [] binds an exec approval to the member who asked. Three
regressions on main let other people answer it:
- Telegram observe mode (#151758): the requester was read from
HERMES_SESSION_USER_ID, the session route, which is empty in an observed
group; may_answer never refused an entry with no requester, so any member
answered. The requester is now HERMES_SESSION_ACTOR_ID/_NAME (falls back to
the route user outside shared chats), and with approvers narrowed an entry
with no requester is answered by listed approvers and admins only.
- Discord buttons (#151762): the view passed the DM-only allow_admin_from list
as admin_ids next to extra, and may_answer unioned it with the group scope's
admins. may_answer now takes ONE admin source (extra -> the approval's own
chat scope, else admin_ids), the same rule as typed /approve; the Discord
view passes only extra. admin_user_ids stays its require_admin click gate.
- Merged multi-sender turns (#151040 review): a busy shared session merged two
members' texts into one turn exporting the FIRST sender as actor while
carrying the second's text. Merging a different sender's input now clears
the event's sender, so the turn exports no actor and the fail-closed rule
above applies (binding to either sender would hand one member's approval to
the other). set_session_vars only falls back to the route user when no actor
is given at all (None), so an explicit "" stays "".
Typed /approve in an observed group now reads the sender from the event
(MessageEvent.sender_id), as the shared source carries no user.
Found by @kshitijk4poor's post-merge review.
Fixes#151758Fixes#151762
The runner publishes the replacement while the old adapter's disconnect()
is still doing task and network cleanup, and that teardown salvages its
buffered text/photo/album batches only at the end. The replacement could
drain a newer event first, and _insert_by_arrival cannot reorder an event
already sent. adopt_held_inbound now salvages a fenced predecessor's
buffered batches up front (popping them, so the later teardown salvage finds
nothing to forward twice).
Greptile thread: "Older messages replay too late" (4511713813).
standalone's _MARKDOWN_CODE_RE matched only single-backtick spans, so in
"**Note**: example ``<b>x</b>`` here" the empty backtick pairs were stripped,
the tag stayed exposed, and the message went out as HTML with its Markdown
markers visible. The HTML/Markdown decision now uses telegram_markdown's
_MD_CODE_RE (same-width backtick runs), the recognizer the MarkdownV2 path
already uses, instead of a second conflicting pattern.
Greptile thread: "Code examples render as HTML" (4511713832).
_TELEGRAM_HTML_TAG_RE stopped at the first `>`, even inside a quoted
attribute, so the new escaping pass turned `<a href="…a>b">` into
`…a>b">` and broke a tag that used to pass through. The tag pattern is now
quote-aware: it ends at the first unquoted `>`.
Greptile thread: "Escaping breaks valid HTML links" (4511713825).
Standalone sends (hermes send, the send_message tool, standalone cron delivery) picked
HTML mode for any supported Telegram tag and sent the text as-is, so a reply mixing
<b> with a model-invented <service> (or a bare < / &) failed Telegram's entity parse
and the whole message degraded. Markup outside Telegram's tag set is now escaped, so
the real tags still render; a supported tag that appears only inside Markdown code
(`<b>x</b>`) no longer flips a Markdown message to HTML mode.
Fixes#142568.
On a cold boot, PTB's start_webhook bootstrap runs delete_webhook then set_webhook as a pair. With bootstrap_retries=0 (the PTB default), a transient failure on the set_webhook half leaves Telegram with no webhook URL while the local listener is already bound. The adapter reports "Webhook server listening" and "Connected to Telegram (webhook mode)" with no error, but inbound updates have nowhere to go — silent inbound loss (#141397).
Passing bootstrap_retries=1 retries the pair on a transient Bot API error. A real config error (rejected URL or secret_token) still fails on the retry, so this does not mask configuration mistakes.
Repro on the issue: the only tell is getWebhookInfo with last_error_message empty after a restart, and a non-zero pending_update_count that does not drain.
When delayed delivery is fenced (disconnect, retryable fatal), an update
that arrives behind the fence is held at once, while text, photo-burst and
album batches buffered before the fence are held later, by their own flush
or by teardown salvage. The hold queue appended in hold order, so the
reconnect drain replayed the newer update before the older buffered one.
An interrupted replay had the same problem: its re-held remainder landed
behind updates that arrived during the interruption.
Each update is now stamped with a process-wide arrival position on first
contact (text, photo-burst and album enqueue), and a batch keeps its first
update's position. `_hold_inbound_event` inserts by that position instead
of appending. The counter is process-wide so positions stay comparable when
a replacement adapter adopts its predecessor's queue (#132829). Unstamped
events keep append order. The teardown salvage loop moves into the
held-inbound mixin, so adapter.py does not grow.
delete_outside_flood_window checked the 5 s inline cap only before entering
_after_window; if another in-flight request extended the chat's cooldown
during the short first sleep, the loop slept the new (possibly minutes-long)
value inline, parking the stream consumer that awaits this cleanup after the
final reply. Every inline wake now re-checks the cap and hands a longer wait
to the tracked background task.
Greptile thread: "Delete cleanup can stall" (4511927264).
_after_window slept on its last iteration and then gave up without checking
whether that sleep had cleared the cooldown, so the old preview stayed. It
now re-checks once after the final allowed wait, as the deferred-media loop
does.
Greptile thread: "Last wait drops the delete" (4511927277).
A 429 retry_after arms the chat's flood window, and sends, edits, typing and
native media already respect it. Draft frames and deleteMessage did not, so
every streaming tick and the end-of-turn preview cleanup kept hitting a
penalty that Telegram extends while it is being hit. Now:
- a draft frame inside the window is skipped (success, raw_response
skipped), because the next frame or the final send replaces it. A 429 on a
rich or plain draft arms the window and keeps the draft transport.
- a delete waits a short window out inline. A longer window is waited out
once by a tracked background task, so the caller is not parked.
- a 429 on either call arms the window for every other path too.
send_draft / delete_message bodies move into telegram_flood_window.py
(adapter.py shrinks).
Fixes#107612
Telegram clients split a long paste into several messages that can reach the
gateway more than 0.3 s apart, so the first part flushed as its own turn and
the rest arrived as a mid-run steer. Text over 1,024 characters now waits
1.5 s for its continuation (2.0 s after a near-4,096 chunk); the 0.18/0.24 s
fast paths for normal-length text are unchanged.
Salvaged from #111162 by @100yenadmin.
Fixes#74752
_MD_CODE_RE matched only single-backtick spans, so ``[k](v w)`` read as two
empty spans and the link degrader rewrote its content to `k`. Inline spans
now close on a backtick run of the same width (CommonMark), the rule
_RICH_DOLLAR_RE's code branch already uses.
Greptile thread: "Code examples lose text" (4511620166).
A connection reset / RemoteProtocolError after sendMessage was written may
already be in the chat, yet the legacy send loop resent it twice and
_send_with_retry retried the whole send again, so one reply could post
several times. send() and the rich path now classify with the shared
telegram_send_errors.send_error_kind: a LOST request (left, no readable
answer) is raised at once and returned delivery_uncertain + not retryable,
which _send_retry_is_final honours (no gateway retry, no plain fallback).
Connect / pool failures (never left) are still retried.
Live (real adapter + PTB, stand-in posts the message then aborts the
connection): 2 visible copies on main, 1 here; connect-refused control is
still retryable.
Fixes#64238
_keep_typing runs per session, but Telegram meters per chat: every DM topic
shares one chat id, so N active topics sent N sendChatAction calls per tick
into one chat, and send_typing walked past the chat's send flood window and
the shared send+edit slot. telegram_typing_gate.typing_may_fire now allows one
typing call per chat per 2 s, stays quiet inside the chat's flood window or
while a send/edit holds its slot, and takes that slot when it fires, so a
send right after a typing call is paced behind it. _typing_in_cooldown moves
into the same sibling.
Live (real adapter + PTB against the Bot API stand-in, three topic sessions
in one chat for 6.5 s): 12 sendChatAction calls on main, 4 here.
Fixes#99643
A model reformatting a session_search result as `[Title](Title)` or
`[Title](@session:profile/id)` got the bracket syntax shown verbatim:
the MarkdownV2 formatter kept any destination, and the rich-message
payload passed the raw markdown through. Both paths now keep scheme URLs
(https:, tg:, mailto:) and bare domains as links and degrade every other
target to its label; code spans and fences stay verbatim.
Fixes#97497
The #81370 drop classified the command itself with hermes_cli.commands.is_interrupt_then_dispatch,
which is not on the published plugin API (boundary_lint failed). The adapter now overrides
_discard_text_debounce, which base calls exactly where it honours /stop, /new or /reset on a busy
session (and on a stale-lock heal), and drops that session's photo bursts and albums there.
An idle chat's /stop or /new does not reach that seam, so a photo buffered just before it still
flushes as a turn on that path.
With observe_unmentioned_group_messages on, _gate_or_observe saved the event
before contact_text ran, so the transcript got only the sender label (a
contact has no text or caption) and a later mention could not use the card.
The contact handler now renders the event first and hands it to
_observe_unmentioned_group_message(..., event=event).
Greptile thread: "Observed contacts remain blank" (4511366274).
- filters.CONTACT handler renders a shared contact (name, phone, vCard) as a text
turn; before, PTB matched no handler and dropped the update silently (#98598).
- /stop, /new and /reset drop that session's buffered photo burst / album, so a
photo sent just before /stop no longer starts a new turn right after it (#81370).
- The module-level ImportError fallback logs its traceback: WARNING for an
installed-but-broken SDK, DEBUG when python-telegram-bot is simply absent (#87455).
New logic lives in plugins/platforms/telegram/telegram_ingress.py; adapter.py
stays at its base line count.
Fixes#98598, fixes#81370, fixes#87455
Co-authored-by: kokhlo <konstantin.khlopkov93@gmail.com>
Co-authored-by: Chen Jin <Enough1122@users.noreply.github.com>
Co-authored-by: liuhao1024 <sunsky.lau@gmail.com>
hermes_platform.host.facts.os_family is not on the published plugin API
(plugin_api.json lists only the bare hermes_platform module), so the new
import failed scripts/boundary_lint.py --check. Use stdlib sys.platform like
the rest of the plugin's per-OS handling.
Greptile thread: "New import fails CI" (4510888063).
max_keepalive_connections=0 (b02b7122f8, #87057) made every ~10 s
long-poll open a new TCP+TLS connection. Each closed socket parks in
client-side TIME_WAIT: two profiles exhausted macOS's 16k ephemeral
range after ~2 days (host-wide EADDRNOTAVAIL), and on Linux/macOS the
~9k daily handshakes turn a small per-connect failure rate into
constant polling gaps. telegram_network.getupdates_keepalive_connections()
keeps 0 on Windows (the CLOSE_WAIT reuse deadlock) and 1 elsewhere,
enough for the single in-flight poll; the standalone sender shares the
builder.
Live: 20 polls through the real build_ptb_requests getUpdates client
opened 20 TCP connections on main, 1 on this head.
Co-authored-by: holny <holny@foxmail.com>
Fixes#107880