Commit Graph

3456 Commits

Author SHA1 Message Date
Teknium
8e31ef1e39 fix(telegram): a prose $$ never pairs across a code span with a later formula
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).
2026-11-10 13:16:03 -08:00
Teknium
a9ec0d8c5f fix(telegram): a mid-line unclosed ``` stays prose, so its $ amounts are escaped
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).
2026-11-10 13:16:03 -08:00
Teknium
f47de3319c fix(telegram): escaped-star check stays linear on long messages
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.
2026-11-10 13:16:03 -08:00
Teknium
ededca00f9 fix(telegram): lone * in bold stays visible; rich $ escape skips all code linearly
#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 #151722
Fixes #151725
2026-11-10 13:16:03 -08:00
qby
3d1424d2e8 perf(telegram): keep a one-line link off the message-prefix scan
`_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.
2026-11-10 13:16:03 -08:00
qby
25baafbacc perf(telegram): answer emphasis span checks with a line index, not a rescan
`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
2026-11-10 13:16:03 -08:00
Teknium
77d6c24afd fix(telegram): a prose $$ never opens math across a fence or paragraph
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.
2026-11-10 13:14:00 -08:00
Teknium
c399bd967c fix(telegram): rich literal scan closes fences and code spans like CommonMark
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.
2026-11-10 13:14:00 -08:00
Teknium
d37a4a036c fix(telegram): inline code spans pair backtick runs in one linear pass
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.
2026-11-10 13:14:00 -08:00
Teknium
5d3103b486 fix(telegram): rich normalization shares one code-region scan and scans emails linearly
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).
2026-11-10 13:14:00 -08:00
Teknium
621f4f2f0b refactor(telegram): rich payload normalization lives in rich_markdown sibling
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.
2026-11-10 13:14:00 -08:00
luyifan
f41424f7c3 fix(telegram): skip rich entity detection for emails 2026-11-10 13:14:00 -08:00
liuhao1024
9ba3ad4164 fix(telegram): separate a non-1 ordered list from the preceding prose on the rich path
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
2026-11-10 13:14:00 -08:00
Brian Le
3fe02d3a40 fix(telegram): preserve literal hash references in rich messages 2026-11-10 13:14:00 -08:00
unsupportedpastels
e4a0f8732b feat(gemini): Interactions API by default for Gemini 3 and later
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.
2026-11-10 11:37:47 -05:00
unsupportedpastels
fbe9216c11 feat(gemini): Interactions API transport in the gemini provider plugin
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.
2026-11-10 11:37:47 -05:00
Teknium
b3746e35dd fix(gateway): a voice clarify reply settles only the question it was checked against
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>
2026-11-09 17:07:28 -08:00
Teknium
d1aed60ec1 fix(gateway): slash confirms and clarify questions answer only to their requester
#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>
2026-11-09 17:07:28 -08:00
Teknium
3b42157858 fix(telegram): a typing tick no longer freezes a group's streamed preview
Some checks failed
Live provider canaries / Live provider canaries (push) Has been cancelled
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).
2026-11-09 16:24:33 -08:00
liuhao1024
74dde239c8 fix(telegram): fallback walk fails over inside the send deadline (#136412, salvage #136427)
Some checks failed
Deploy Site / deploy-vercel (push) Has been cancelled
Deploy Site / deploy-docs (push) Has been cancelled
auto-fix lint issues & formatting / Generate eslint --fix patch (push) Has been cancelled
auto-fix lint issues & formatting / Apply patch (push) Has been cancelled
Skills Index Freshness Check / check-freshness (push) Has been cancelled
Skills Index Freshness Check / check-catalog-cors (push) Has been cancelled
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.
2026-11-09 15:43:50 -08:00
Teknium
007d7e8b50 fix(telegram): retired adapters edit and delete through their same-profile replacement (#98228, #143364)
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.
2026-11-09 15:43:50 -08:00
salch-cred
6c93005fe7 fix(telegram): replacement adapter resolves inside its own profile
_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.
2026-11-09 15:43:50 -08:00
ducky_56789
039262515c fix(telegram): keep seed IPs behind DoH-discovered fallback IPs (#75416, salvage #76685)
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.
2026-11-09 15:43:50 -08:00
Teknium
a6c4e29937 fix(telegram): a root message after a threaded follow-up never adopts the new topic
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.
2026-11-09 15:33:28 -08:00
Teknium
2243a114d1 fix(telegram): an adopted topic opener is not overtaken by threaded follow-ups
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.
2026-11-09 15:33:28 -08:00
Teknium
d2011903cc fix(telegram): log when allowed_topics drops a forum topic
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.
2026-11-09 15:33:28 -08:00
Teknium
5532919d31 fix(telegram): split admission lanes only for real topic messages
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.
2026-11-09 15:33:28 -08:00
Ravi Tharuma
2af49ba3e2 fix(telegram): isolate DM topic update lanes 2026-11-09 15:33:28 -08:00
Kevin Rajan
0a5b42e1a0 fix(feishu): clear mixed-sender approval actor in shared bursts
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.
2026-11-09 15:17:08 -08:00
Teknium
b77ee87c44 fix(approvals): bind narrowed approvals to the real sender, in one admin scope
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 #151758
Fixes #151762
2026-11-09 15:17:08 -08:00
Teknium
8c96f17457 fix(telegram): a replacement adapter takes the old one's buffered batches before it replays
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).
2026-11-09 15:02:49 -08:00
Teknium
385ff1fe4a fix(telegram): hermes send treats a tag inside a double-backtick span as a code example
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).
2026-11-09 15:02:49 -08:00
Teknium
2903e03e4a fix(telegram): hermes send keeps an HTML tag whose quoted attribute holds >
_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&gt;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).
2026-11-09 15:02:49 -08:00
Teknium
239609fdb1 fix(telegram): hermes send keeps HTML formatting past a model-invented tag
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.
2026-11-09 15:02:49 -08:00
Shoaib Latif
0151c2f613 fix(platforms/telegram): retry webhook bootstrap once on transient Bot API failure
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.
2026-11-09 15:02:49 -08:00
千乘妍 (Xiaoyaner)
cfb6f6e7b3 fix(telegram): replay held inbound in arrival order
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.
2026-11-09 15:02:49 -08:00
Teknium
91c7c07b95 fix(telegram): a delete never sleeps a re-extended flood window inline
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).
2026-11-09 15:02:49 -08:00
Teknium
430d864cb0 fix(telegram): a delete whose flood window closes during the last allowed wait still runs
_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).
2026-11-09 15:02:49 -08:00
Teknium
7222595b82 fix(telegram): streaming drafts and deletes stay out of a chat's flood window
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
2026-11-09 15:02:49 -08:00
Eva
ed74264afe fix(telegram): a long paste split by the client stays one turn
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
2026-11-09 15:02:49 -08:00
Teknium
033b6c8530 fix(telegram): link-shaped text inside a double-backtick code span stays verbatim
_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).
2026-11-09 15:02:49 -08:00
Teknium
e98a7006f8 fix(telegram): a send reset after the request was written is never resent
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
2026-11-09 15:02:49 -08:00
Teknium
5948ab52e2 fix(telegram): typing keep-alives send one call per chat and share its outbound budget
_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
2026-11-09 15:02:49 -08:00
Teknium
a0d954f62d fix(telegram): links Telegram cannot open render as their label, not raw syntax
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
2026-11-09 15:02:49 -08:00
Teknium
82bdce51ad fix(telegram): /stop and /new drop buffered photos through base's own debounce discard
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.
2026-11-09 15:02:49 -08:00
Teknium
51ed48a8e3 fix(telegram): an observed unmentioned contact card keeps its contents
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).
2026-11-09 15:02:49 -08:00
Teknium
d742bfddc6 fix(telegram): contact cards reach the agent, /stop drops buffered photos, SDK import failures name their cause
- 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>
2026-11-09 15:02:49 -08:00
Teknium
a633070733 fix(telegram): getUpdates keepalive branches on sys.platform, not an unpublished core name
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).
2026-11-09 15:02:48 -08:00
Teknium
48d57b63f5 fix(telegram): getUpdates reuses one socket off Windows instead of a fresh TCP per poll
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
2026-11-09 15:02:48 -08:00
stepanov1975
642bb293db fix(gateway): scope editable statuses to each turn
Fixes #92210
2026-11-09 15:02:48 -08:00