adapter.py is far over the file-size cap and this PR grew it. Move the
payload canonicalization, the safe per-command sync, and the install-scope
helper into a DiscordCommandSyncMixin module; adapter.py ends 133 lines
shorter than main. Code is moved unchanged.
A reconnect could replace the client while application_info() was in
flight, and the old client's result was then stored and applied to the new
one. Capture the client before the call, and stop if it changed by the time
the call returns; the new client's READY runs its own sync. Clear the memo
when connect() builds a new client and on disconnect, so it no longer holds
a closed client.
Tests: named scope scenarios, including a new client ignoring the old
client's refresh and a replacement mid-refresh; the reconnect test asserts
the memo is cleared.
Bound the application_info() refresh at 15 s so a stalled call can't hold
post-connect forever. When it fails, reuse the last refresh for the same
client instead of the login-time snapshot, which can be older than settings
already synced; the snapshot is used only before any refresh succeeded.
Tests: one subprocess runs every scope case, adding the failed-later-refresh
and changed-between-READY cases; the remaining safe-sync test uses
_sync_adapter.
A command whose description AND install types both differed took the PATCH
path. discord.py's edit_global_command sends only name/description/options,
so the install types stayed stale while the sync recorded success, and the
fingerprint then skipped every later start. Upsert whenever anything a PATCH
cannot carry differs.
Read the Installation settings from a fresh application_info() at each sync
instead of the login-time snapshot, which a reconnect reuses after a settings
change. A failed refresh falls back to the snapshot.
Tests: share _sync_adapter across the safe-sync tests, cover mixed drift and
description-only edits, and cover the refresh and its fallback.
Hermes left integration_types/contexts unset, so each command kept whatever
Discord stamped on it at creation. Commands created while the app was
user-install only stayed integration_types=[1]; other members of the bot's
server got "Unknown Integration" on /new, /status, /model, /stop and /reset,
and no sync could repair them.
Derive both from the app's own Installation settings (application_info's
integration_types_config, already fetched at login) before every sync. The
hardcoded [0,1]/[0,1,2] would be refused by Discord on a guild-install-only
app: a command can only use install types the app enables, and the
private_channel context needs user install. When the settings are
unavailable the tree stays unset, as before.
Agents stamped as gateway_hygiene after construction (hygiene and manual
/compress) re-resolve their auto tier after the stamp, so they stay on 5m
while context engines still bind to the real platform at construction.
Request-time clamps carry the auto flag, so a session that moves to Bedrock
mid-session under auto drops to 5m; an explicit 1h pin is kept. The Feishu
comment agent change is reverted (it changed the system prompt, not the tier).
Gateway-routed one-shots (hermes -z, chat -q), messaging /background, a2a and
msgraph_webhook sessions, the gateway hygiene agent and the Feishu comment
agent are machine-paced and now resolve to 5m under auto. Bedrock resolves to
5m under auto (legacy Claude models there accept only 5m); an explicit 1h pin
is kept. Interactive CLI, TUI, Desktop, ACP and messaging chats stay on 1h.
Main's new or changed cases that seeded or read the old store run on the storage interface with main's assertions: the observed transcript timestamp, the observe-mode /resume ownership guard, the dead private topic prune and the kept binding of an unconfirmed send, the oversized file admission, the idle /new that drops a held burst, the adoption of a chat on an external-process provider, and the send-path recovery sweep after a profile stop. Rows are seeded through the storage handle, the ledger's store follows the test's HERMES_HOME, and each authority's stores close by profile folder.
The private topic send ladder's docstring names the interface verb that prunes a dead topic's binding.
The Feishu comment bot's five tools (feishu_doc_read and the four
feishu_drive_* tools) answered "Feishu client not available" on every call.
feishu_comment stored the Lark client in a threading.local on the thread
that starts the agent, and since ededa8c4f1 the agent runs each tool call
on a worker thread. The worker gets a copy of the caller's context
variables, not its thread-locals.
The client handle is now a context variable in tools/feishu_lark.py, set
and reset by token around the agent run. The handle's row in
gateway/turn_thread_reset.py goes, because nothing is keyed by thread any
more. The bot's reply was never affected: it is posted outside the tools.
tools/microsoft_graph_auth.py and tools/microsoft_graph_client.py register
no tool and only Teams code imports them, four of six imports from
plugins/teams_pipeline/. They move there as graph_auth.py and
graph_client.py, with their two tests under tests/plugins/teams_pipeline/.
- Importers change one import line where it stands; summary_writer.py
keeps its imports inside _build_graph_client.
- The Graph client's only core import, parse_retry_after_seconds, is on
the published plugin API.
- boundary_lint baseline drops the 8 rows for these imports; an import of
another in-tree plugin is not a crossing (module_to_core 833 -> 825).
- The Graph app registration guide and its zh-Hans copy name the new path.
- Nothing stays at the old paths; neither module is on a frozen list.
Measured: with teams_pipeline disabled, Graph delivery from the Teams
summary writer still works, but its first call now imports the
teams_pipeline package (17 Hermes modules instead of 2), because
plugins/teams_pipeline/__init__.py imports its CLI.
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.
Removed. A search for callers by name, attribute and string (Python, TypeScript,
docs, the plugin API list and the frozen old-updater list) finds no supported
path that reaches any of them:
- tools/send_message_tool.py: _handle_list, _handle_react and the action
dispatch in send_message_tool (every caller, including the external
hermes-snooze plugin, passes action="send")
- tools/bot_failure_reasons.py: is_auto_retryable
- tools/clarify_gateway.py: _notify_cbs, _coerce_text_response,
attempt_text_response_for_session, resolve_text_response_for_session
- tools/cronjob_tools.py: the unused task_id parameter of cronjob()
- tools/interrupt.py: is_thread_yield_requested
- toolsets.py: create_custom_toolset
- tools/tool_backend_helpers.py: prefers_gateway, REMOVED_BACKENDS,
removed_backend_note, normalize_modal_mode (callers use coerce_modal_mode)
- hermes_cli/config_value_checks.py: _validate_web_backends (only read the
always-empty REMOVED_BACKENDS map)
Tests that existed only for these symbols are deleted; tests that also
cover live behaviour now call the canonical live names
(attempt_text_response, _coerce_text_response_detailed, consume_yield).
The shared-bot route-gate tests that reached the gate through the deleted
react action now call _shared_bot_target_allowed directly, so the origin
rules (guild-only, thread-under-channel and user_id routes, Telegram topics,
the turn's sender in a shared channel) keep their coverage. The two error
hints and one comment that named send_message(action='list') now name
`hermes send --list`; the stale send_message row in the zh-Hans tools
reference goes.
Also:
- test_messaging_slash_command_fifo spies on clarify_gateway.attempt_text_response,
the name gateway/run_inbound.py calls, so its [clarify] case can fail again
- send_message_tool: an action other than 'send' returns an error that names
`hermes send --list` for listing targets
- multi-profile-gateways.md no longer says send_message sends reactions; the zh-Hans
simplex.md and tools-reference.md match the English pages
Turning on ruff preview (needed for PLW1514, unspecified-encoding) also
widens some stable rules. Clearing what it reports first lets the config
change that enables it land with no ignore list:
- evals workers: 20 text-mode open() calls get encoding="utf-8".
- a2a and weixin adapters: legacy "# type:" comments become annotations.
- agent/lsp/client.py, gateway/run_turn.py: two prose comments started a
line with "type:", which type checkers read as a type comment.
- sorted(x)[0] becomes min(x) (plugins_session_env, one test).
- test_plugin_session_fork: the attempts default is built per call
instead of a shared list inside a tuple.
The pinned ruff 0.15.22 passes with today's config and with preview on.
BlueBubbles runs on the owner's own Apple ID, so marking a stranger's DM
read showed "Read" from the owner before the runner's authorization check.
Gate mark_read on the same verdict the attachment download already uses.
Refs #149024
#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 reaction gate now consults the gateway auth check, which can change
during a turn (the message that trips a bot's loop-guard budget passes
at start and fails at completion). Key the completion on the 👀 sent at
start; re-check the verdict only before the outcome emoji.
Refs #108353
Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
The attachment fetch gate called the gateway auth check without is_bot, so a
bot_users sender on the human allowlist got the human verdict and its
attachments were fetched while its chat was in loop-guard cooldown. The
SessionSource is now built before the gate and its is_bot is forwarded, the
same way the reaction gate does it (keyword only when set, so 3-arg callbacks
keep working).
Refs #108353
Only a whitespace-only BlueBubbles password is treated as unset; any other value
is used exactly as configured, both in the requests sent to the server and in the
webhook compare. Before this, .strip() altered passwords with leading or trailing
spaces.
Signal's pre-auth reaction gate now forwards source.is_bot, so a bot_users sender
gets the gateway's bot verdict (loop-guard cooldown) and a refused bot gets no 👀.
Refs #108353
Rejecting a bad webhook signature now returns the same 404 as an unknown
route, so the pin/V1/forged-challenge tests and the docs that still named
401 for signature rejections follow. The Feishu replay-window case ran only
with lark_oapi installed although the signature check never needs it, and
the quota tests signed with a fixed 2023 timestamp that the new window
refuses. The shared-helper test still imported BlueBubbles from its old
gateway/platforms path.
Fixes#108353Fixes#108388Fixes#127901Fixes#136768
on_processing_start fires before the gateway's authorization gate. With SIGNAL_ALLOWED_USERS unset the adapter's DM allowlist is "*", so when the operator authorizes through GATEWAY_ALLOWED_USERS or pairing, any sender still got the eyes reaction, revealing a listening bot. Consult the registered authorization check as well and skip the reaction when it returns False.
X-Twilio-Signature covers only the URL and form fields, with no nonce or timestamp, so a captured signed POST replayed later passed validation and started the same turn again. Track recent MessageSids in a MessageDeduplicator (24h TTL, bounded) after signature validation and acknowledge a repeat with empty TwiML without dispatching. The cache is carried across adapter rebuilds by carry_inbound_dedup.
The webhook check compared the request token to the configured password with !=, and a whitespace-only password counted as set, so a webhook sending the same blanks was accepted. Strip the password (connect() already refuses an unset one) and compare UTF-8 bytes with hmac.compare_digest, failing closed when the password is empty.
Two webhook auth hardening gaps:
- bluebubbles compared the inbound token with != instead of the
hmac.compare_digest pattern used by the other adapters. It now compares
UTF-8 bytes (compare_digest raises on a non-ASCII str, and the token is
attacker-controlled) and fails closed when no password is configured.
- The generic webhook adapter returned 404 for unknown routes but 401
for a known route with a bad signature, so route names were enumerable.
Bad signatures now return the same 404 (the profile-mismatch path
already did exactly this). The webhook docs' response tables follow.
BlueBubbles, the Google Meet node and WeCom compared remote-supplied secrets
with ==/!=. WeCom and Feishu verified a signature over a timestamp they never
checked, so a captured callback verified forever once message-id dedup
forgot it. The timing-safe compares elsewhere used provided.encode(), which
raises on the surrogate-escaped bytes aiohttp hands over, and A2A compared
str to str, which raises on any non-ASCII token: a 500 instead of a 401.
The compare and the 300 s window already existed privately in webhook.py.
They move to gateway/platforms/_shared.py as secrets_match and
timestamp_fresh (WEBHOOK_REPLAY_WINDOW_SECONDS), and every inbound compare
uses them. The Meet node keeps a stdlib-only inline compare because its
protocol module is deliberately free of gateway imports.
Fixes#127901
Co-authored-by: Bartok9 <259807879+Bartok9@users.noreply.github.com>
Co-authored-by: Adolanium <94890352+Adolanium@users.noreply.github.com>
Co-authored-by: zapabob <130830376+zapabob@users.noreply.github.com>
Co-authored-by: memosr <memosr_email@gmail.com>
Co-authored-by: zashraf1337 <6955094+zashraf1337@users.noreply.github.com>
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>
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
npm ci from a lockfile never consults min-release-age; the mirrored
.npmrc only matters for the npm install fallback's fresh resolve.
Refs #134019
Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
Follow-up to the salvaged #134062 commit. Drop its repo-walking
structural test (banned shape per tests/AGENTS.md) and instead assert the
read-only-tree mirror actually carries .npmrc to where npm ci runs. The
.npmrc comments now say what the gate mirrors: the root .npmrc carries
only engine-strict; the 14-day floor lives in pnpm-workspace.yaml's
minimumReleaseAge, which npm never reads.
Fixes#134019
npm reads project config only from the directory that owns the
package.json, so scripts/whatsapp-bridge and plugins/platforms/photon/
sidecar never inherited the root .npmrc's min-release-age=14 and their
lockfiles resolved without the cooldown - pinning versions published
days earlier (#134019).
The bridge holds WhatsApp session credentials, parses inbound messages
from arbitrary senders, and the gateway npm-installs exactly the locked
versions for every user (_ensure_bridge_deps), so the gate cannot be
applied user-side.
- add scripts/whatsapp-bridge/.npmrc and plugins/platforms/photon/
sidecar/.npmrc with min-release-age=14, matching the root
- include .npmrc in the photon sidecar _MIRROR_FILES whitelist so the
read-only-tree mirror keeps the gate where npm ci actually runs
- add a structural guard test: every directory with a package-lock.json
must carry a .npmrc with the same floor