#151809 held a short text for the image sent right after it. Forward-with-comment and
"here's the clip:" then a clip send the TEXT first too, but for video, voice, audio and
documents the comment still flushed alone and the attachment became a second turn. The
media handler now claims the pending comment for any attachment and the generic dispatch
path absorbs it, the same claim/absorb seam the image path uses.
Co-authored-by: mene-crab <mene-crab@proton.me>
The progress, proxy and queued follow-up paths called send_typing directly, so the
opt-out still sent a chat action after every progress edit. The check now sits at
the one sendChatAction call. Documents the opt-out for clients that move the view
while the indicator is on (#40885).
A longer fence keeps ``` runs inside its code; the search-and-splice loop then matched
those runs as a new block, deleting them and leaving a stale MONOSPACE length. Build the
unwrapped text and ranges in a single finditer pass over the original text.
Refs #146848
Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
code_fence() wraps a command that contains ``` in a longer backtick run, but
the formatter only knew three-backtick fences, so the ``` inside the command
closed the block and the rest of the command was restyled on the approval
card. Match any fence length with a backreference, in the code-block pass and
in the bullet/table fence splits.
Refs #146848
Follow-up to the salvaged fix: seeding `occupied` with code ranges stops
code from being restyled, but finditer still let a `**` inside a fence
pair with one in the prose after it; that overlapping match was dropped
and consumed the real pair, so the prose kept raw markers. Scan only the
gaps between code blocks. Adds a round-trip test that each issue command
in a fenced approval prompt reads byte-identical while prose is styled.
Refs #146848
- Protect fenced code blocks by pre-populating occupied spans so inline patterns cannot match inside them
- Skip heading matches that fall inside existing code blocks to avoid converting comments to bold headings
- Shift code block ranges when preceding headings are stripped
- Prioritize inline monospace backticks so inline code spans cannot be split by bold or italic markers
- Add comprehensive regression test suite in test_signal_format.py
Signed-off-by: crustdev <dev@crusts.dev>
The Interactions transport (default for Gemini 3+/-latest on AI Studio) let
any function_call step override an incomplete/budget_exceeded status, and the
long-decode hop ceiling reported tool_calls when a call had streamed, so a
cut-off call executed. Report tool_calls only when the status maps to stop;
the hop ceiling always reports length. Also pin the native stream case where
finishReason arrives in a later event than the functionCall.
Fixes#144949
Review follow-ups on dm_threads: shared (Greptile on #155680):
- text batches stay per DM thread (the session key drops the thread, a merged
batch kept only the first event's source, so a second thread got no answer)
- /topic state is read from the source's pinned runtime profile store, not the
active scope (a primary bot routing to another profile keys before scoping)
- a hot reload of dm_topics updates config.extra too, so a topic added while
running stays its own session
- the shared copy uses session_identity.replace_source (keeps provenance)
- a rebuilt source with no live adapter ref (/loop, restored routes) reads the
answering bot's settings through the runner's delivery resolver
Review findings on #155645:
- 'Some finals still lose quotes': a final edit that lands after a short flood wait now runs the
same bookkeeping, and an oversized final indexes its edited first chunk and every continuation.
- 'Saved quotes change code': quotable_text() strips MarkdownV2 only outside code spans/fences.
- 'Write failures stay silent': rich_sent_store.record/record_async return False on a failed write
(still never raising) and the adapter logs on that result.
- 'The oversized adapter keeps growing': _edit_overflow_split moves to telegram_overflow_edit.py;
adapter.py is now below its origin/main line count.
Indexing the finalized text pushed edit_message's complexity over its
ratcheted cap; the saturated-preview dedup and the final's index write now
sit in one helper. Also maps @AlexGogin's commit email for attribution.
Trim the salvage to its fix: drop the quote-touch refresh (a synchronous
index rewrite on the event loop for every quote-reply, with no report of
eviction in practice) and the HERMES_RICH_SENT_MAX_ENTRIES env knob
(behaviour config does not go in env vars). Replace the mocked unit tests
with two real-gateway invariants against the Bot API stand-in: a
quote-reply to a plain send and to a streamed final, whose echo carries no
body, still reaches the model as [Replying to: "..."]. Both are red on the
base (the quoted text is missing) and green here.
Refs #147287, salvage of #151125.
Telegram does not echo a message body back in reply_to_message, so the adapter
resolves the quoted text from its own sent index (gateway/rich_sent_store). Only
the rich send path (sendRichMessage) wrote that index; the ordinary MarkdownV2
sendMessage path - which carries the vast majority of outbound messages - wrote
nothing. A user quoting such a message therefore produced an inbound event with
reply_to_message_id set and reply_to_text empty: the agent answered a question
whose subject it could not see, and nothing in the logs showed why.
- record the sent text on the legacy send path and on the legacy finalize edit
- refresh a quoted entry's timestamp so the FIFO trim keeps it
- make the index cap configurable via HERMES_RICH_SENT_MAX_ENTRIES
- log a warning when a quoted body is unrecoverable (the loss was silent)
- tests: tests/gateway/test_telegram_sent_text_index.py
On a multiplexed gateway, a routed profile's direct FAL image or video job
went out signed with the launch profile's FAL_KEY, so it was billed to the
launch profile's FAL account. Hermes' own check (fal_key_is_configured) reads
the routed profile's scope and says "configured", but the submit then used
the module-level fal_client.submit: one process-wide SyncClient() that reads
os.environ (the launch profile's .env, loaded at gateway start) on first use
and keeps that key for the life of the process.
Both direct sites now submit through tools.fal_common.direct_fal_client(),
which builds fal_client.SyncClient(key=...) from the same key the check reads
(new tool_backend_helpers.fal_key(), shared with fal_key_is_configured). One
client per key, reused, as the managed client already is. Unscoped
single-profile runs read the same key as before: get_secret falls through to
os.environ there.
The unscoped submit shapes came from 95dc9aaa75 (rewbs, 2026-03-26, #3287,
image) and d04b3c193e (alt-glitch, 2026-05-27, #33259, video). They became a
cross-profile leak once routed profiles started sharing one process.
Part of #151791 step 9-pre (tracker #152308): explicit per-profile SDK keys.
Modal, Vercel token mode and HF upload are separate follow-up slices.
Greptile: Custom proxy routes stop working. bot_api_urls appended /bot to any
path not ending in bot, so base_url https://proxy.example/telegram/ moved to
/telegram/bot<token>; it now appends only when the URL has no path, for
base_url and base_file_url alike.
PTB appends the bot token straight to base_url, so `extra.base_url:
http://127.0.0.1:8081` became `...8081123456:AA...` and httpx parsed the
token's secret half as a port: every connect attempt failed with
InvalidURL("Invalid port: '<secret>'") (#81787). bot_api_urls() appends the
Bot API `/bot` (`/file/bot`) path when the URL doesn't already end in `bot`
or carry PTB's {token} placeholder; the gateway adapter and the standalone
sender both use it.
Self-chat rejections logged the full chat/sender id of every other chat
on the owner's account, unconditionally; they now go through
redactWhatsAppId() like the debug events. libsignal's console.info
session dumps (private/root/base keys) are collapsed to their label by
the console wrapper, which now also covers console.info. bridge.log
rotates to one .1 generation above 5 MB when the adapter opens it at
spawn, and full/pre-update backups skip both generations.
Fixes#149860
* fix(security): keep the BlueBubbles password out of gateway logs
Every BlueBubbles request carries the server password as ?password=.
Two paths wrote it to agent.log in clear:
- Inbound: on the shared listener that serves multiplexed profiles,
aiohttp's default access logger records the full request target; the
adapter's access_log=None only applies when it binds its own runner.
RedactingFormatter now masks credential query params on aiohttp.access
records (the strict URL pass, which ordinary logs keep off so OAuth /
magic-link URLs survive).
- Outbound: httpx.HTTPStatusError text embeds the request URL. The
adapter's log lines and SendResult.error now go through one helper that
applies redact_url_credentials.
Fixes#143550Fixes#146420
* test(security): pin every BlueBubbles REST error path and the access-line gate
Each remaining _safe_error site (register, unregister, attachment upload,
attachment download) now has a real httpx 401 test, and a RedactingFormatter
test pins that only aiohttp.access records get the strict URL pass.
Refs #143550
Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
---------
Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
* fix(plugins): keep config-selected plugin names inside their plugin root
memory.provider, cron.provider and context.engine were joined onto the
plugin root unchecked, so a path-shaped name loaded a package from
anywhere. Worse, the "is bundled" test was lexical (Path.parents), so a
`<root>/../..` spelling counted as bundled and was imported in-process
even under plugins.isolation: host. Names must now be a plain directory
segment (invalid = not found, so the built-in fallbacks apply), and the
bundled test compares resolved paths.
Fixes#141328
* fix(plugins): a user-dir symlink into the bundled root is not bundled
is_direct_child compared resolved paths only, so $HERMES_HOME/plugins/<x>
linking into a bundled dir counted as bundled and loaded in-process past
plugins.isolation: host (and the link could be swapped between check and
import). Require the path to sit under the root both as written and resolved.
Refs #141328
* test(plugins): satisfy ruff PLR0402 and cover the resolved half of is_direct_child
Use `from plugins import ...` instead of aliased submodule imports (ruff
PLR0402 failed the Python lints lane). Add a bundled-root child symlink that
resolves outside the root, so dropping the resolved comparison in
is_direct_child is caught.
Refs #141328
Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
---------
Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
Greptile: Split replies still carry quotes. The split-anchor rule moves into
telegram_split.split_reply_anchor and send_rich_parts applies it before
_deliver_parts, so an opted-out split rich reply carries no reply_parameters.
Docs state the streamed-reply limit (anchor chosen at the first preview; an
edit cannot remove it).
Some Telegram Desktop/TDLib clients hide the first part of a multi-part reply
when it carries a native reply anchor (#55059). The default keeps today's
anchor on part one; `platforms.telegram.extra.anchor_multipart_replies: false`
sends a split reply unanchored. Single-message replies keep their anchor, and
private DM-topic sends keep it because the topic routes by it.
Suppression rule from #55060 (@ooiuuii), gated behind the opt-in.
Co-authored-by: ooiuuii <ooiuuii@users.noreply.github.com>
Check the final address on both parse paths, not only the bracketed fallback:
an unterminated quote made parseaddr return 'victim@x, attacker@evil' verbatim
(reply RCPT TO both, authenticated by the attacker's domain), and
'victim"@evil' re-parsed as the bare recipient 'victim'. Authentication now
folds domains A-Z only, like the identity, so U+212A cannot pass as 'k'.
Fixes#136770
A bracketed 'Doe <victim:x@evil>' passed the single-addr-spec check and its
reply To: parses as a group, so the recipient differs from the chat_id. The
self-address check now uses the same ASCII-only fold as the parsed sender.
Fixes#136770
The sender identity was lowercased with str.lower(), which maps
U+212A KELVIN SIGN to ASCII k, so `Kevin@x.com` (Kelvin sign) became
kevin@x.com and matched an allowlisted kevin@x.com. Sender
authentication only proves the domain, so anyone with mail at that
domain could take the allowlisted identity. The parsed address and the
allowlist entries now fold A-Z only, and the gate no longer re-lowercases
the already-folded address.
The single-bracket fallback took whatever sat between < and >, so
`Doe <victim@x.com,attacker@evil.com>` parsed to
`victim@x.com,attacker@evil.com`. That string became the chat_id and
the reply To:, and smtplib sends to both. The bracketed part must now be
one addr-spec (one @, no , or ;); anything else is an unparseable sender
and the message is dropped like any other malformed From:.
<TOOLCALL> (Nemotron-style text tool calls) was missing from the shared tool-call tag
tuples, so strip_think_blocks and the CLI renderer let it through to the delivered text;
that is how it reached Telegram in the first place (#61217). Add it to both tuples, so
closed, cut-mid-JSON and stray-closer forms are dropped like <tool_call>.
Move the reply redaction from the Telegram adapter into gateway reply_pointer: it now
covers every platform's quoted reply, already-sent messages, and adds no new
plugin-to-core import. Match the tag case-insensitively like the other tool-call tags.
When a user replies to a bot message whose content carries raw internal
<TOOLCALL> markup from the agent's output stream (echoed text, native
quote, or the rich_sent_store send-time index), the Telegram adapter
exposed the markup verbatim via reply_to_text, leaking protocol details
into the user-facing reply preview and the injected reply context.
Redact <TOOLCALL> blocks (closed and truncated-unclosed) with a
[processing...] placeholder at the single point where reply_to_text is
resolved in _build_message_event. Plain messages pass through unchanged.
Closes#61217
Greptile round 1 on #153107:
- "Shutdown forgets flood windows": the flood-window writer is no longer a
_background_tasks member (shutdown cancels those). disconnect() awaits it
shielded, together with the update-receipt flush (land_persisted_state).
- "Later profiles miss restart notices": the whole replay waits until the
boot pass reaches a notice (it captures the replay context then), so a
heal while secondary profiles still connect cannot discharge the
planned-restart marker against a partial profile set.
- "Restart confirmation arrives too early": a replay only answers the
requester marker the boot pass read, and no replay runs while this process
drains for a restart, so the next /restart's marker survives for its boot.
Also: a requester send cancelled mid-flight keeps its marker; only a definite
outcome or an exception consumes it.
A 429 retry_after arms a per-chat window inside which Telegram sends fail
closed locally, but the window lived in memory only. A gateway restart during
a ban forgot it, and the new process's first reply, stall notice or heartbeat
went straight back into the penalty (#89962). The window (moved out of
adapter.py into telegram_flood_cooldown.py) is now also written per bot to
telegram_flood_cooldown_<bot id>.json in the adapter's own profile home and
loaded on the first window check after boot. Entries carry a wall-clock
deadline, are clamped to the 300 s window cap on load, and expire on their own.
Boot-time restart notices raced Telegram's send-path readiness (#66589): the
adapter refuses sends with send_path_degraded until the polling generation's
first getUpdates, _send_restart_notification unlinked .restart_notify.json
in finally either way, and the planned-restart "online" notice was replayed
only when the adapter was REPLACED, never when it healed in place. Now
(gateway/run_notifications_restart.py):
- the requester marker is kept while the platform has no live transport or
refuses with the reconnect-only error the delivery ledger already uses
(is_reconnect_only); permanent refusals and suppression still consume it,
and a kept marker expires after 30 minutes;
- one replay (requester + planned-restart) runs on every reconnect and on the
Telegram adapter's degraded -> healthy edge, in the boot pass's context and
under one lock, so the notice goes out once.
Live (real gateway + Telegram stand-in):
- flood: 429 retry_after=200, SIGTERM, boot, new turn. main: 1 sendMessage
into the window; head: 0 (refused locally, 193 s left).
- notice: getUpdates 502 for the first 45 s of boot. main: neither notice
sent, the requester marker deleted; head: both sent once polling healed,
no markers left.
Fixes#89962, fixes#66589
One rule instead of two ad-hoc ones: a reply aimed at a known card (live or
ended) counts only from that card's author, and any other private-chat text
from the author answers their newest live card.
- A private-chat code sent as a reply to some unrelated message fell through
to chat text: the reply-target branch returned before the private fallback.
- Ended cards now remember their author, so another member's reply to one is
their own message and is never deleted.
From review of the Telegram code card:
- Cards were keyed by (chat, author), so an answered card's timer ended the
author's next card early and two cards overwrote each other. Each card is
now its own record keyed by (chat, card message id), and its timer retires
only that card.
- A reply to a card whose request had ended fell through to the normal text
path, so a late code reached the agent as chat text. Ended cards are
remembered (bounded), and a reply to one is deleted and never becomes a turn.
- delete_message() returns True for a delete queued behind a long flood wait,
which skipped the "please delete it yourself" warning even if the queued
delete later failed. The interception uses delete_message_confirmed().
- In a group, ForceReply(selective) opens the reply field only for users the
card mentions, so the card now carries an invisible mention of the author.
Test doubles of the telegram package (test_telegram_thread_fallback.py builds
its own module tree) do not define ForceReply, so importing it at adapter
import time failed the whole try block and left ChatType and friends unset.
The code card imports it when it is sent.
Telegram has no private form a bot can open, so the code arrives as a normal
message. telegram_vault_code.py implements the send_vault_code_prompt hook
the gateway already detects (gateway/session_vault_code_card.py): a ForceReply
card aimed at the turn's author. Their next text in that chat (a reply to the
card in a group, any text in a private chat) is taken off _handle_text_message
after the auth check and before batching: the bot deletes it, hands the code
to submit(), marks the card, and never builds a MessageEvent.
- A different member, or an unrelated group message, is not taken as the code.
- A failed delete (a group where the bot lacks delete rights) posts a notice
asking the author to remove it.
- python-telegram-bot logs every getUpdates result and webhook body at DEBUG;
while a code reply is pending those records are dropped.
- Strings: platform.telegram.vault_code.{body,delete_failed} in all 17 catalogs.
From an independent review of the head:
- code_card_scope's exit set each request's event but kept its value, so a
code submitted while the card's send was still unacknowledged survived the
turn's end and was entered once the ack landed. Exit now cancels the
request (event set AND value cleared), and wait() reads the value under the
request lock with the stop flag.
- discord.py (DiscordWebSocket.received_message) and slack_sdk Socket Mode
("Received message") log every received frame at DEBUG, before any handler
runs, so with logging.level: DEBUG a modal submit wrote the code into
agent.log. Each card module installs a logging.Filter on those SDK loggers
that drops frames carrying its own input id (Discord's TextInput now has a
fixed custom_id) or view callback id. Other frames still log.
The boundary lint counts each new plugin-to-core import per file; the
Slack facade already imports agent.i18n.t, so the sibling late-binds it
from there instead of adding a crossing.
When a site texts or emails a one-time code during a Slack-driven sign-in,
browser_vault enter_code answered prompt_unavailable: no code prompt was
installed for messaging turns. The Discord commit before this one adds the
messaging-turn code callback (gateway/session_vault_code_card.py) and its
send_vault_code_prompt adapter hook; this gives Slack the same hook instead of
a second broker and BasePlatformAdapter surface (#130569's shape).
- plugins/platforms/slack/adapter_vault_code.py: a Block Kit card with an
"Enter code" button carrying an opaque token. Only the turn's author, in the
workspace the card was posted to, can open the modal; anyone else gets an
ephemeral refusal. The view_submission value goes straight to submit() and
the card is rewritten without its button. A submit after the request ended
is refused in the modal and enters nothing. The code is never posted,
echoed or logged.
- The card strings move from platform.discord.vault_code to
platform.shared.vault_code (all 17 catalogs) so both adapters read one set.
Co-authored-by: Chukwuebuka Ezeokeke <ebulamicheal@gmail.com>
vault_prompt_scope installs the vault callbacks only for local-viewer
(Desktop/TUI) turns, so on Discord `browser_vault action=enter_code`
returns prompt_unavailable and a sign-in whose code arrives by SMS or
email cannot finish from chat (#141844).
A messaging turn whose adapter implements send_vault_code_prompt now
gets the code prompt (gateway/session_vault_code_card.py). Discord
implements it in a new sibling, adapter_vault_code.py: an "Enter code"
card whose button opens a modal for the turn's author only (base
allowlist admission still applies), so the code goes from the modal
submit to the waiting agent thread and is never posted, echoed or
logged. The wait runs in 1 s slices that honor /stop and feed the
inactivity watchdog. A failed send, a timeout or an interrupt returns ""
(code_declined), and the scope's exit releases a tool thread that is
still parked on a card.
can_prompt_here() keyed only off the unlock callback, so a surface that
installed the code prompt alone was reported as unable to ask. It now
takes the callback the caller is about to use. Only enter_code passes
one; unlock and save_login keep their answer on every surface.
Other messaging adapters, cron, webhooks and the API server are
unchanged: no send_vault_code_prompt means no callback and still
prompt_unavailable. Unlock and save_login are not offered on chat
platforms.
Closes#141844
_download_external_media_with_cap kept its own copy of the
Content-Length + streamed-size check; route it through the same reader
as the inbound mxc path so the cap lives in one place. The image/* type
check stays outbound-only.
Refs #55041
mautrix 0.21.1 Client.download_media() returns `await response.read()`,
so an event that omits or under-reports info.size had its whole body
buffered (and cached) regardless of MATRIX_MAX_MEDIA_BYTES.
Move the capped request into plugins/platforms/matrix/media_download.py,
mirroring download_media (same URL helper, v1.11 auth header, request
logging) but streaming under the cap, and drop the event when the cap is
crossed instead of falling back to the HTTP URL. Replaces the salvaged
commit's in-adapter helper, whose unittest.mock detection kept the
unbounded path reachable, and keeps the facade from growing.
Fixes#55041
After an unconfirmed (timed-out) checkbox edit _toggle keeps the flip. If
that edit never landed, the user's corrective re-tap asks for exactly the
markup Telegram already shows, Telegram answers 400 "message is not
modified", and that was classified as a refusal: every later tap toasted
"tap again" and Send submitted a lost tick (or refused a visible one).
"Not modified" proves the card already shows the requested selection, so
commit it instead of reporting a failure.
_toggle treated every NetworkError as an ambiguous delivery and kept the
flip. A connect failure (httpx.ConnectError through PTB's HTTPXRequest,
surfaced as telegram.error.NetworkError) proves the edit never reached
Telegram, so the card still shows the old ticks while Send would submit
the hidden pick.
Classify the failure with telegram_send_errors.send_error_kind, the same
classifier the senders use: only MAY_HAVE_DELIVERED (timeout/lost or a
Telegram 5xx) keeps the flip; refused, flood-waited and never-sent edits
keep the old selection and answer the tap with toggle_failed.
The gateway can clear or time out a pending clarify while Telegram's
edit_message_reply_markup is awaited. _toggle then still recorded the
checked option and answered "Selected: 1" on a question the agent no
longer accepts. Recheck after the await that the same pending entry is
still registered (identity, so a re-registered id is not mistaken for it)
and retire the card with the expiry notice instead.
Approach and regression test from kvnloo's add-on 5255eecfdd9 on the PR
review; this version compares entry identity rather than any pending
multi entry.
Co-authored-by: Kevin Rajan <7121943+kvnloo@users.noreply.github.com>
Review follow-up on #154925:
- A toggle updates the saved selection only after Telegram accepts the
keyboard edit. A refused edit (BadRequest) keeps the old ticks and the
old selection, and the tap gets a "tap again" toast, so Send never
submits a pick the card does not show. An unconfirmed edit (timeout)
keeps the flip, because it may have landed.
- A toggle or Send tap on a card whose question already ended (timed
out, answered by text, session reset) retires the card with the
expired notice instead of answering "Invalid choice" forever.
Follow-up to the contributor's toggle/Send keyboard (#154195):
- Send resolves the clarify with a JSON array of the checked labels, the
shape the typed "1, 3" reply already resolves to. The comma string the
tap path sent decoded as ONE answer ("Nuxt 3 (Recommended), Go
Microservice") with the display label left in.
- The toggle/Send handling and the shared resolve step move to
telegram_clarify_multi.py so adapter.py shrinks (6715 -> 6708 lines)
instead of growing.
- The four new prompt strings are translated into every locale catalog.