A labelled mention such as <#C1|dev_ops_alerts> or <!subteam^S1|@eng_team_x>
was split by the italic regex on its underscores before the leaf mention
split ran, so Slack showed the token literally with a stray italic run.
The label is dropped from the element anyway, so drop it up front.
rich_text does not interpret mrkdwn, so <@U…>, <#C…>, <!subteam^S…> and
<!here|channel|everyone> tokens inside lists, quotes and table cells were
emitted as text and rendered literally. Split them into user/channel/
usergroup/broadcast elements at the emphasis leaf so surrounding bold/
italic/strike spans survive.
Fixes#133315. Squashed from #133323 (095821f, 53c8268, fcf7c97, 9fd0327).
Baileys reports the delivery status of messages Hermes sends
(`messages.update` with `update.status` in 1:1 chats, a per-recipient
`message-receipt.update` in groups), but the bridge only handled poll
updates there, so operators could not see whether a reply was delivered
or read.
The bridge now queues a `delivery_status` event for status changes of its
own sends (tracked IDs only, so messages typed on the linked phone are
never reported). The adapter logs one gateway.log line per change and
never dispatches it as an inbound message.
The reaps now wait out a SIGTERM grace (up to 6s each) with time.sleep, and
connect() called them inline on the loop every platform shares, freezing
Telegram/Discord/etc. while a slow WhatsApp bridge exited. Run them via
asyncio.to_thread. The psutil-fallback test reads /proc of every process,
which names files under the real Hermes home on a box running Hermes, so
it opts out of the home write guard.
Replaying the branch onto main linearly resurrected port_accepts_listen, the
duplicate helper the branch dropped when it merged main (#140186 already
gives port_is_free the bridge's SO_REUSEADDR semantics). Restore the merged
tree: one helper, one contract.
The port-free wait used a plain bind probe, which Linux refuses while the
previous bridge's closed connections sit in TIME_WAIT (up to 60s). node's
listen sets SO_REUSEADDR and succeeds then, so a normal restart failed with
whatsapp_bridge_port_busy after 10s and waited for the reconnect backoff.
Probe with SO_REUSEADDR on POSIX so only a live listener blocks the spawn.
connect() SIGTERMed the previous bridge, slept a blind 1s and spawned the
new one regardless. A bridge that was slow to exit (or ignored SIGTERM)
still held 127.0.0.1:<port>, so the new bridge died on EADDRINUSE and the
reconnect loop retried the same race forever.
- _kill_port_process / _kill_stale_bridge_by_pidfile wait out a SIGTERM
grace, then SIGKILL survivors after re-checking identity (a PID recycled
inside the window is never signalled).
- connect() replaces the blind sleep with a bounded bind-probe wait for the
port and fails with a named retryable whatsapp_bridge_port_busy instead
of spawning onto a busy port. A holder that is not our bridge is still
never killed.
- Listener discovery falls back to psutil when neither lsof nor ss is
installed; without it the scan was silently empty and nothing was reaped.
- A bridge that dies during the post-spawn health wait no longer leaves a
dead-PID bridge.pid; disconnect() waits for a force-killed bridge to exit.
- bridge.js handles the listen error and exits with a clear EADDRINUSE
message instead of an unhandled stack trace.
When a click records the answer but Discord rejects the interaction
edit, the view was stopped but the card kept its pending embed and
dead buttons. The settle observer skips cards whose click owns the
edit, because `_backend_settled` was already set.
Now a failed edit after a recorded answer clears `_backend_settled` and
retires the card through its message: buttons removed, "already
resolved" footer. The retire runs under the same lock as the
observer's, so only one of them edits. The edit error is still raised,
as before. A failed edit on a no-op click (nothing recorded) is
unchanged.
Tests:
- The edit-failure case of test_click_stops_view_even_if_interaction_edit_fails
now asserts the card is retired.
- A new test fires the observer during the failing edit (the usual
order, since the waiter wakes before Discord answers). The observer
skips, and the click's own retire stamps the card.
Both fail on the previous commit. The new test also fails with only
the retire call removed.
Reported by Greptile on #145948.
adapter.py was already far past the 2,000-line limit, and this stack
grew it from 7,414 to 7,512 lines. AGENTS.md lets a unit that is
already over the limit only shrink. The file's FILE_LINES allowance
covers an earlier platform-table move, not the approval code.
ExecApprovalView now lives in adapter_exec_approval_view.py. Its body
moved verbatim: build_exec_approval_view(discord, base, unauthorized=...)
returns the class, and _define_discord_view_classes assigns it to the
same module global as before. The one change inside the body: the
failed-lookup log now carries its traceback (exc_info=True), which the
health check requires of a catch-all in a new file. A builder is needed because discord.py
can be installed lazily after the adapter is imported, and the other
views are defined the same way. adapter.py ends at 7,374 lines, 40 below
main.
Item 1 of the review is only partly fixed by the stale-click commit
before this one. Clearing `_backend_settled` lets the settle observer
retire the card, but the click still edited the same card with
"Approval expired — command was not run" through its own interaction
response. Nothing serializes that edit with the observer's. If the
click's edit lands last, it hides the real outcome and reattaches the
disabled controls. Discord serializes the interaction payload before
awaiting the response, so a later embed change can't repair it.
When a click on a card with a request id resolves nothing, that request
has already settled through another path. Since the earlier commits, its
observer is always registered (it is registered before the send, and a
request gone before that already retires the card). So the click now
only answers the clicker privately ("no longer pending") and leaves the
card edit to the observer.
A click whose lookup raises recorded nothing, and its request may still
be pending. It used to stamp the card "expired — not run" and disable it
for good, and that edit could race the observer too. Now it re-opens the
card for a retry, tells only the clicker ("Couldn't record your choice.
Click again, or answer with /approve or /deny." — a new string in every
locale), and leaves the final edit to the observer. A card without a
request id has no observer, so its no-op click keeps the old "expired"
edit.
Tests:
- The stale-click regression now asserts that the click never edits the
card. It fails on the previous commit.
- A new test drives a failed lookup on a really pending request with its
observer attached: the card stays live, and a later text answer
retires it with the real outcome.
- A third test pins the expired edit on a card with no request id.
Raising the `discord_prompt_timeout` cap to the platform-safe maximum
makes a gap much larger. Slash-confirm, update and clarify views never
called `stop()` when answered; only exec approvals did. discord.py keeps
an unfinished view registered after the answering edit, and its timeout
task sleeps until expiry with no upper bound.
So every answered prompt stayed registered for the whole configured
timeout, now up to a year. When the timeout finally fired, the base
`on_timeout` stamped "Prompt expired — no action taken" over "Approved
by X". The overwrite already happened on main within 900 s; the higher
cap only delays it.
`_finalize_embed` (slash confirm, update, exec approval) and the clarify
`_finish` now stop the view in a `finally`, after the answering edit, so
an edit failure still releases it. The exec view's own `finally: stop()`
is now covered by `_finalize_embed` and goes away.
New parity test: an authorized answer on each of the three views (and
the clarify "Other" hand-off) leaves the view finished. All four cases
fail on the previous commit. Exec cards stay covered by
test_discord_approval_lifecycle.
The card registered its settle observer only after `channel.send`
returned. If the request ended during the send (wait timed out, /stop,
session closed, withdrawn), the registration found no entry and the card
retired with the default reason "resolved". The card then said "This
approval has already been resolved" for a command that never ran.
Build the view first and register the observer before sending. A reason
that arrives while the card is still in flight is held on the view
(`pending_retire`) and applied as soon as the card exists. Only a
request that was already gone before the card was built still has an
unknown outcome. That card now says "⌛ This approval is no longer
pending (it timed out or was answered elsewhere)", a new outcome-neutral
string, translated in every locale. It no longer claims either
"resolved" or "not run".
Building the view outside `_build` also removes the `view_holder` list
that only existed to get the view back out. The view never depended on
the channel.
The test now covers the three orderings (after, during, before the send)
and asserts the footer. Two of them fail on the previous commit.
The runner tunnelled the approval request id to Discord as a private
`_approval_request_id` key inside the platform metadata dict. That dict
goes to every adapter that renders approval buttons. The relay adapter
forwards it verbatim, so the private key reached the external connector
in every approval prompt frame.
Add an optional `request_id` to `send_exec_approval` and to
`ExecApprovalPrompt`, have the runner pass `approval_data["request_id"]`,
and have Discord read `prompt.request_id`. The metadata passed to the
adapters is back to the thread routing it carried before the PR (`None`
in a plain chat). The always-true `"timeout_s" in approval_data` guard
goes with it.
Native-button adapters render through `_send_exec_approval_prompt`,
whose signature is unchanged. The only `send_exec_approval` override,
`LocalSessionAdapter`, takes `**kwargs`, as does every test double, so
no other adapter or double changes.
A stale button click that resolves zero gateway approvals must not mark the backend settled and suppress the already queued resolved observer. Cover the external-answer to stale-click race through the real component gate.
_is_sender_authorized already returns None when no check is registered, which the click path treats as a denial. No Feishu test double relies on the extra getattr.
With Feishu admins or FEISHU_ALLOWED_USERS set, an approval or update-prompt click was compared by open_id only, while message intake accepts open_id, tenant user_id and union_id. A user listed by tenant user_id could message the bot but not answer its cards. The click now matches any of the ids the card callback carries (open_id, user_id, union_id), on both the callback thread and the loop-side re-check.
With no Feishu admins and an empty FEISHU_ALLOWED_USERS (the setup default), any chat member could answer an exec-approval or update-prompt card. The clicker now has to pass the same gateway authorization inbound messages use (pairing store, GATEWAY_ALLOWED_USERS, allow-all flags); the click is refused when that check denies or is not registered. A configured Feishu admin/allowlist still decides on its own.
Every cache keyed on a file's stat signature had the bug the config caches had: a same-size
in-place rewrite in one coarse timestamp tick keeps mtime, ctime, size and inode, so the older
parse was served for the rest of the process. Move the helper to utils.file_cache_version
(file_signature + content digest while the file is under 2 s old; always_digest for signatures
compared much later, where the racy digest going empty would read as a change) and key every
cache that can hold a secret, token, pairing/allowlist, route or config on it:
- auth.py: global auth-store memo, Nous auth-status memo (was mtime only)
- gateway/pairing.py approved-users cache (a revocation kept access)
- run_profile_reconcile: served-profile signature (always_digest: a false change reconnects
adapters) and the hook-consent signature
- webhook dynamic routes (route HMAC secrets), Feishu comment pairing/rules cache (mtime only)
- MCP OAuth tokens-file reload check (mtime only; always_digest: a reload tears the session down)
- config parse-failure record (always_digest), named-custom-provider memo, model aliases,
gateway.standalone memo, profile model read, MoA preset, agent raw config,
tui_gateway raw config cache, onboarding due stamp, free-tier inventory stamp,
provider model-list credential fingerprint, git safe.directory key, skills prompt
manifest
config_cache_version takes its stat through config_version, so its errors and seams are unchanged.
Left alone: the tool-definition cache key and the platform manifest stamp (a safe worker must
never open config.yaml or a plugin file; the MoA preset cache is skipped in one instead) and the
CLI MCP watcher seed (pinned to file_signature by a main test).
Add tests that a token-authenticated listener still serves a foreign Host, that malformed Host values fail closed, and that a no-token POST without a Content-Type is refused. Give the no-token Host rule its own README bullet and document every 403 refusal message.
The no-token Host check accepted only localhost, 127.0.0.1 and ::1, so other loopback literals and a local reverse proxy forwarding the configured A2A_PUBLIC_URL host were refused. Accept any loopback literal and the A2A_PUBLIC_URL host, name both in the 403 message and docs, and document the Content-Type refusal.
Keeps the loopback-name check consistent with the hermes proxy one: a
trailing dot names the same host, while a rebound name stays refused
with or without it.
(cherry picked from commit 5d1c94588affb445638426653e2230132c741ec6)
Without a token the listener trusts whatever reaches 127.0.0.1. A page on a hostname
that re-resolves to 127.0.0.1 is same-origin to it and could read /health (the
served-agent list), the Agent Card and /metrics. parse_request now refuses such a
Host with 403 before any route runs; a malformed Host fails closed. Token mode is
unchanged.
Fixes#126203
(cherry picked from commit 7d71a6082e325eee0880ea82542cce7db2459517)
Without a token the A2A listener identifies callers by the loopback
socket alone, which a web page open in the operator's browser can also
reach. In that mode, refuse a POST that carries an Origin header, a
Sec-Fetch-Site other than none/same-origin, or a non-JSON Content-Type
(the body types a page can send without a CORS preflight). Token mode
is unchanged.
(cherry picked from commit cfb36d3c5f30fc205c5d0ef122e43dd482bcfc91)
Under multiplex, authorization reads each profile's own secret scope, so the
DISCORD_ALLOWED_USERS the YAML bridge copies from discord.allow_from into os.environ is never
seen. The fallback to the adapter's extra then read group_allow_from for 'group' sources:
Telegram's group-only list, which Discord does not have. An allowlisted user's guild-channel
messages were dropped and their button clicks refused, while threads and DMs worked.
Discord declares allow_from_covers_groups, so its groups read allow_from. Adapters with a
separate group list (Telegram) are unchanged; a test pins that a Telegram DM-only allow_from
still does not admit the user in a group.
#133213 confirms a snapshot-admitted clicker with the gateway's live check, but labelled every
guild click 'group' and passed no thread id. Message intake labels the same channel 'thread',
so a user the gateway admits in a thread could be refused on its approval card ("This bot is
private..."), and a thread_id profile route never matched the click. Label the click like
intake does: a discord.Thread is 'thread' with its id as thread_id.
CI on the salvage was red on the code-health ratchet (over-cap facades grew; two blind excepts)
and on the pm observer fixture, whose isolated source tree carries pm/ + hermes_cli/ but no utils.
- config_backend imports become module-level in the facades (it imports only stdlib); gateway,
auth and telegram take config_exists through the hermes_cli.config import they already have.
- Pure helpers move to topical siblings, offsetting the growth: _csv_or_list_to_set ->
gateway/run_common.py, the dotted config-path pair -> hermes_cli/backup_restore.py, the
voice/timezone/web-backend checks -> hermes_cli/config_value_checks.py, _load_config_dict ->
hermes_cli/profile_memory_config.py (both callers are memory-provider code).
- _load_config_dict catches YAMLError/OSError/UnicodeError instead of Exception.
- _load_config_cache_hit probes readability with config_backend.probe_config_readable (a 1-byte
read through the backend's open) instead of a full parse plus a blind except.
- pm/plugins_state.read_home_selection checks config_exists before importing the YAML stack, so
a home with no config never needs utils.
- developer-guide/config-backend.md describes this build (file backend only).
Same approach as @benbarclay's 74421be709 in #122509, which does not cherry-pick onto current main.
Add hermes_cli/config_backend.py (config-config design §4.1, D10/D11): a
ConfigBackend protocol, the FileBackend (today's behaviour), selection by
HERMES_CONFIG_BACKEND only (default file; 'remote' and unknown values fail
closed with ConfigBackendUnavailable), and path-level helpers
(read_config_doc, read_config_doc_readonly, config_version, config_exists,
write_config_key, write_config_document, supports_file_tooling).
Migrate every direct reader/stat/exists/bypass writer of a user config.yaml
to the helpers (config.py loaders + caches, config_effective, env_loader,
gateway, TUI, CLI watchers, cron, tools, profiles, logging, time). File
tooling (config edit, backups, xAI migration rewrite, raw dashboard editor)
checks supports_file_tooling() first; migrations skip write-back without it.
Add scripts/check_config_yaml_readers.py (CI lint next to the writers gate)
that rejects a direct read of a config path outside the backend.
Every CLI start imports all provider plugins (hermes_cli.config lists their env vars), and
fireworks/gmi/xai/router/kimi/opencode plus auth_constants, models, model_catalog,
auxiliary_client, gemini_native_adapter, web_server_messaging, slack, yuanbao and perplexity
built a `<product>/<release>` string at module level. In a source checkout the release comes
from the 7-call git provenance walk (`git tag --merged HEAD` alone is ~0.35 s in a large
clone), so `hermes sessions list` paid it for headers it never sends.
Provider profiles take a LazyHeaders mapping (resolved on first read by the client builders,
which already copy with dict()); core modules call version_info.hermes_user_agent() where the
request is built. Header values are unchanged.
- Feishu routed .ogg/.opus to an "audio" (voice) message by extension even
for send_document / is_voice=False; Opus is now an audio message only when
the caller requested one.
- Discord _ogg_opus_duration walks page headers by segment table instead of
rfind("OggS"), which could match packet data and misread the granule.
- Tests: successful transcode path (bytes, duration, temp removed), OggS run
inside packet data, Feishu plain .ogg/.opus and the voice-intent control.
Same class as the Discord and Feishu fixes: these adapters' send_voice
ignored is_voice, so a plain audio MEDIA file (music, a sound effect)
became a voice note. The WhatsApp bridge always sends "audio" as ptt
(transcoded to Opus), WhatsApp Cloud converted every local mp3 into an
Opus voice bubble, and BlueBubbles flagged every file isAudioMessage.
is_voice=False now goes as a named document (WhatsApp bridge), as the
original audio/mpeg (WhatsApp Cloud), or as a plain attachment
(BlueBubbles). Voice intent and the no-flag auto-TTS path are unchanged.
The media dispatch routes every audio MEDIA file to send_voice with is_voice,
but the Discord adapter swallowed the flag and uploaded every file as a native
voice message named voice-message.ogg (audio/ogg), whatever the bytes were.
A sound-effect mp3 or a wav arrived as a voice note that does not play, with a
duration guessed from the byte size (mutagen is not a dependency).
is_voice=False now goes out as a regular attachment under its real name.
Voice intent ([[audio_as_voice]], auto-TTS) sends real Ogg/Opus: non-Opus
input is transcoded with ffmpeg, without ffmpeg the original goes out as an
attachment, and duration_secs is read from the Ogg granule position.
The deferred tool_search catalog shows each tool's first sentence clipped to
60 chars, so lines like 'image_generate: Generate high-quality images from
text prompts, or edit /…' hid that it edits with reference images on the
user's configured model. An agent skipped it and called FAL directly with a
hardcoded model.
- catalog line cap 60 -> 80 (CATALOG_SUMMARY_MAX_CHARS); every built-in
tool's first sentence now fits and leads with what it does
- image_generate/video_generate say they use the configured model;
image_generate says to use it rather than direct API calls/scripts
- web_search/web_extract/browser_exec name when to use each other
- drop a duplicated cronjob sentence and filler in skill_view/video_generate
- regenerate tests/fixtures/prompt_surface
Folds the two IPv6 server classes into one: every IPv6 host gets
AF_INET6, and V6ONLY=0 makes the :: wildcard answer IPv4 too.
A dual-stack socket reports an IPv4 peer as ::ffff:a.b.c.d, so the
shared-token / no-token identity became ip:::ffff:127.0.0.1 and an
A2A_TRUSTED_PEERS entry written as ip:127.0.0.1 no longer matched
(403 "peer not trusted"). _client_ip unmaps it. The test drives a
token-gated :: bind over both stacks plus an IPv4 tasks/list call
behind an IPv4 allow-list.