tools/ holds model tools. These three files register none: they send a
message to a platform for `hermes send` and for cron delivery, through
gateway adapters and gateway config. They move to the gateway package:
tools/send_message_tool.py -> gateway/outbound/send.py
tools/send_message_senders.py -> gateway/outbound/senders.py
tools/send_message_targets.py -> gateway/outbound/targets.py
Twelve test files move with them to tests/gateway/outbound/. Every importer
changes its import line in place. Nothing stays at the old paths: none of
the three names is on the plugin API list, the shipped-release list or the
old-updater list.
Behaviour is unchanged. The logger name stays tools.send_message_tool in
the three files and in the QQ Bot sender that shares it, so the lines stay
under `hermes logs --component tools`. The boundary-lint baseline changes
12 keys and no count, because its keys carry the module path of the
underscore names five bundled plugins import.
The import and docs rewrites were made by scripts/move/rewrite_imports.py
and rewrite_docs.py.
#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).
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
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.
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>
<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.
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.
_UrlEmphasisScan probed each mark run inside a URL as a candidate closer for
emphasis opened before the URL. _star_token already skipped a backslash-escaped
first star for pairing, but the fallback cut used run.start(), so the escaped
star landed in the closer and the URL lost it:
`***Docs https://ex.com/a\** now` showed `*Docs https://ex.com/a\ now`
(main: `**Docs https://ex.com/a\* now`). `**x https://ex.com/a\** z` was
already wrong at 6b7e6cb6, and escaped `~~`/`||` marks were cut the same way.
The scan now starts a URL run after an escaped first mark (odd backslash run),
so that mark stays URL text and only the marks after it may close; a run that is
only the escaped mark is skipped.
Rows for the four re-review shapes added to
test_emphasis_around_a_url_pairs_as_around_any_word, and
test_no_bare_url_loses_a_character_to_formatting gains backslash-escaped
*, **, ~~ and || shapes (9 red on 8dd38f4f). Both fix-lane corpora (1,526
rows): 0 regressions vs main or 8dd38f4f, 0 URLs losing characters, 0
MarkdownV2 errors; 160k-input fuzz: 0 non-mark characters lost; 20k/80k/320k
timing stays linear.
_UrlEmphasisScan kept its own star-run bookkeeping, which treated a run as one
indivisible opener. The renderer (_pair_emphasis) closes PART of a run, so for
`***bold* https://example.com/**` the scan saw separate `***` and `*` openers,
refused the URL's final `**` as a closer, and the stars stayed escaped inside
the URL while e4b1353c and main rendered bold.
The pairing loop of _pair_emphasis moves into _StarPairing (feed = pair for
real, probe = dry-run with an undo journal) and _star_token; _pair_emphasis
and the scan both drive it, so a URL star run closes exactly what the
renderer would close: partial runs, reach past literal `*` (`**rm *x
https://x/y**`), the rule of 3. The scan's rule is otherwise unchanged: a mark
run inside a URL is URL text unless it closes emphasis opened before the URL;
a later prose closer wins unless the URL run would have spent that opener.
Probes are bounded by _CLOSER_LOOKBACK, so the scan stays linear.
Greptile P2 4567931541.
Four rounds of URL-emphasis heuristics (right-to-left reopen/closer sets, /-run budgeted
re-pairing) each exposed a new edge; the latest cut `https://example.com/a*;b*c*` at the first
star and rendered `;b` italic, dropping two URL characters (Greptile 4567531365).
Replace them with one left-to-right scan: prose delimiters (`*` runs, `~~`, `||`, line and
paragraph breaks) keep a stack of open emphasis. Inside a URL, the first mark run with prose after
it that matches the innermost open marks is that emphasis's fallback closer; every other mark is
URL text. A later prose closer of the same emphasis wins (`*Open https://x/a*;b*c* now*` keeps the
URL whole); an opener left unclosed at its line/paragraph end, or by an enclosing closer, takes the
fallback and the URL ends there. Linear: each delimiter is pushed and popped once, and a URL run
looks at most 8 openers deep.
Adds the Greptile row, a strike twin and a property test over 56 internal-punctuation URL shapes x
11 wrappers: every URL is shown whole, or cut only at a run closing outer emphasis.
`_closing_mark_run` (54c8d0b9) let any later run of the same marks that continued as
URL text "reopen" the URL, so in `**https://example.com/a**,next**word**` the
`**word` opener made the URL swallow its own closing `**`: one bold span with
literal stars instead of bold URL then bold `word`. In the right-to-left pass a run
that a later closer of the same marks pairs is now an opener, not URL text, so it no
longer reopens the URL; `a*;b*c` and `a**,b**c` (no closer after the reopener) stay
whole URLs.
The paragraph re-pairing used for `/`-ended runs cannot decide this: both readings
leave 0 unpaired marks for `Open u*;b*c now` and for `**u**,next**word**`, so it
would turn `a*;b*c` back into italics. Review corpus (616 rows): byte-identical to
54c8d0b9, 0 regressions vs main; 910 internal-punctuation rows: 112 change vs
54c8d0b9, every one to main's rendering (0 rows differ from both).
browser_exec display masking: `params = {**params}` rebinds a name to itself, so
_dict_text followed the spread back to the same name forever (RecursionError);
masking runs before dispatch, so the browser call never ran. _dict_text now
tracks the names it followed (as _strings does), and a walk that still fails
masks every string literal in the snippet instead of raising (fail closed).
Telegram bare URLs: the first mark run followed by punctuation ended the URL even
when a later run of the same marks reopened it, so `https://example.com/a*;b*c`
was cut at `a` and `*;b*c` became italics. A run now closes emphasis only when no
later run of the same marks continues as URL text (one right-to-left pass); the
616-row review corpus renders byte-identical to the previous head, and the new
internal-punctuation rows match main or fix it, with 0 regressions.
_MarkRuns guessed emphasis closers from run parity on the URL's line, so
bold across a newline (**See\nhttps://x/**), nested emphasis
(*outer **https://x/** end*) and a closer followed by prose
(**https://x**—next, [**https://x/**]) rendered as literal stars where main
formats them. A mark run with prose after it now always ends the URL (main's
reading); only the ambiguous run right after a trailing '/' (/web/* vs a
closer) is decided by the real _pair_emphasis pairing over its paragraph:
kept as URL text only when that leaves fewer marks unpaired. The decision is
budgeted so a huge reply stays linear.
Placeholder restore did one whole-text str.replace per placeholder, and every
bare URL now adds one (30k URLs: 0.05s on main, 7.3s on head). Values are
expanded in insertion order and the text in one regex sub.
The per-URL tail check stripped only marks and `.,;:!?)`, so a closing quote
(`"*https://example.com/*"`) left an empty tail and the closer was never
released, keeping the `*` inside the URL. The tail now strips exactly what
`_url_end` may trim (`_URL_TAIL_CHARS` plus `)`), so quoted italic, bold and
strikethrough URLs render as they do on main.
`_MarkRuns.closers` advanced the per-line closer count for every URL inside open
emphasis, even one ending in plain text (`https://a.example/x`). The next URL
then saw an even count and kept the sentence's closing `*` as URL text, leaving
the opener unmatched. A mark now counts as closing only when this URL's own
tail actually carries it.
A trailing `*`/`_`/`~` after `/` is judged against the emphasis marks of the
surrounding prose only: runs inside any bare URL (`/web/*`) are URL text and
are no longer counted. The next prose run of the mark is checked instead of
the parity of everything after the URL, so the sentence's own closer (`now*`)
keeps the earlier URL's wildcard as URL text, and URLs on one line are judged
left to right so two emphasized URLs still pair independently.
- redact_browser_input: an Input.insertText call that passes a name
(**params, positional params, {**params}) also masks the "text" value
inside the dict literal assigned to that name.
- telegram_markdown: a trailing */_/~ after "/" closes emphasis iff an odd
number of that mark's runs precede the URL on its line and an even
number follow it, so `*https://a/* and *https://b/*` renders both
italic. Run offsets and line bounds are precomputed once per call and
bisected per URL (O(text + urls log n)).
- telegram_markdown: a trailing */_/~ after "/" closes emphasis when the line
before the URL leaves an odd number of that mark's runs open and the mark
does not recur after the URL on the line ("**bold https://x.com/**",
"*see https://x.com/docs/*" render as on main again); wildcard paths stay URL text.
- redact_browser_input: also mask type_text(...), fill_input selectors with
parens/commas (selector parsed as a literal), f/r/b-prefixed literals, and the
literal assigned to a name later passed as a typed value. text= is read only
inside the insertText call; .value ==/=== is not an assignment.
A trailing * _ ~ right after a / is kept as URL text so wildcard paths like
/web/*/example.com/* survive. When the URL itself opens with that same mark
(*https://example.com/*, **...**, ~~...~~), the trailing mark is the closer of
the emphasis around the URL, so it is trimmed off the URL again.
- Typed values are found by a linear literal scanner: a backslash escape never ends the literal,
triple-quoted values are whole, and an unclosed literal masks to the line end (fails closed).
- A `*`/`_`/`~` right after a `/` stays part of the URL (`/web/*`), so an italic sentence around a
wildcard URL cannot borrow its last character as a closer.
- URL tail trimming counts parentheses once instead of rescanning per trailing `)`.
- The poll-ack test waits with tests.waiting.wait_until instead of a sleep loop.
to_markdown_v2 escaped a bare URL char by char after the emphasis pass, so `*`, `~~` or `||`
inside it paired into italic, strike or spoiler marks: Telegram dropped the characters or hid
part of the URL (#40667). Bare scheme URLs are now stashed whole behind the existing placeholder
and escaped as literal text; trailing prose punctuation stays outside, and a `)` stays only while
it closes a `(` in the URL.
adapter.py grew 6,705 -> 6,710 lines on this branch; files over the 2,000-line
cap may only shrink. Move the @username "Chat not found" hint (now shared by
the gateway send path and standalone_send) and _classify_send_exception into
telegram_send_errors.py, which already owns send-failure classification.
explain_username_chat_not_found accepts a standalone result dict or a gateway
SendResult, so the adapter calls it directly. adapter.py: 6,710 -> 6,692
(main: 6,707).
An in-process adapter send bypasses standalone_send and therefore teknium1's #154923 diagnostic. Reuse that diagnostic at the live send boundary, preserving numeric-id and unrelated failures.
Regression: test_live_gateway_username_home_error_explains_numeric_id
(cherry picked from commit 25f26daa2185912c04574e32a9be56bf639eacd9)
The Bot API resolves @username only for public channels and supergroups. A
home channel set to a person's handle (TELEGRAM_HOME_CHANNEL=@name) makes
every `hermes send --to telegram`, send_message and standalone cron delivery
fail with Telegram's bare "Chat not found", while an explicit numeric
telegram:<id> target to the same chat works. The standalone sender now
appends the cause and the fix (numeric chat id via /sethome or
TELEGRAM_HOME_CHANNEL) when the refused chat id is an @username; numeric ids
and other errors are unchanged.
E2E: the real `hermes send` CLI against the Bot API stand-in, red on main.
Fixes#95121
Resolves the docstring conflict in tools/environments/local_env_policy.py
additively: keeps main's HERMES_MODEL/DELEGATION/CUSTOM/PROVIDER key names and
this branch's HERMES_BRIDGED_* marker note.
Extend HX017 to transcript/user_display and getattr(obj, "<name>", ...) and move the five INFO
sites it then flags (Discord/run_voice transcript, Discord mention-only display name, Telegram
approval/clarify first name + choice text) to lengths/ids. The Discord expired-interaction
WARNING logs only the slash verb. Where link() is refused the salt is created with O_EXCL, and
a failed salt read is cached per home so log calls stop retrying file I/O.
Refs #46006
Gateway and adapter logs reach `hermes debug share` uploads, whose redaction covers
secrets only, so message bodies, subjects, display names, e-mail addresses and the
inbound-message preview were being published verbatim. INFO+ lines now carry lengths,
platform ids or a short `hash_for_log` digest; the raw value moves to DEBUG.
HX017 (scripts/code_health/py_rules_log_content.py) flags INFO+ log calls in gateway/
and plugins/platforms/ whose args are content-named values (text, body, subject,
user_name, display_name, sender_addr, ...). It is name-based on purpose: ids are not
matched, and transport payloads (resp.text, error_text) are skipped. Every existing
hit is fixed or waived with a reason, none baselined. Policy documented in
gateway/AGENTS.md and ADDING_A_PLATFORM.md.
Refs #46006