Commit Graph

3004 Commits

Author SHA1 Message Date
Teknium
ae596f49a0 fix(telegram): an edit of an older lobby message keeps its room (#136567)
Message.date of an edit is the ORIGINAL send time, so an edit of a root-DM
message sent before the topic creation passed the send-time window (negative
gap) and was adopted into the new topic, consuming the record the real opener
needed. A message dated before the creation is now left alone and the record
stays for the opener.

Found by Greptile on #141751.

Live (real gateway + Telegram stand-in): edit an old lobby message right after
creating a topic, then send the opener. At 5e0eb93 the edit went to the new
topic; now the edit stays in the previous topic and the opener lands in the
new one. Slow-photo, split, interleaved-DM and late-lobby cases unchanged.
2026-10-19 21:47:53 -07:00
Teknium
406580697a fix(telegram): time the new-topic follow on send time, not handler time (#136567)
The 5 s follow window was read from time.monotonic() when each handler ran.
PerChatUpdateProcessor holds a chat's next update until the previous handler
returns, so a thread-less photo whose download (or STT, or a document's
caching) outlasted the window pushed the text sent right after it out of the
new topic, into the previous topic or the root DM.

The window now compares Telegram's Message.date stamps (set when the user
sent the message, untouched by queueing). A creation without a date is not
recorded. The local clock only bounds memory (records older than 600 s are
pruned; the oldest is evicted at the 256 cap).

Found by Greptile on #141751; root-caused and fixed in a proposed diff by
@PRELVAS94, adapted here.

Live (real gateway + Telegram stand-in, photo download held 7 s, text sent
right after): before, the text went to the old topic; after, both land in the
new topic. Split opener, interleaved DM and late-lobby cases unchanged.

Co-authored-by: PRELVAS94 <86016656+PRELVAS94@users.noreply.github.com>
2026-10-19 21:47:53 -07:00
Teknium
bda200183d fix(telegram): follow a new DM topic by time, not message-id adjacency (#136567)
The adoption of a client-created topic's thread-less opener required
message_id == creation + 1. Private-chat message ids come from ONE sequence
shared by every private chat of the bot account (bot replies included,
core.telegram.org/api/updates "Common message ID sequence"), so any message
in another DM, or a bot reply, between the creation and the opener broke
adjacency and the opener misrouted to the previous topic again. One-shot
adoption also split a long opener the client sends as several messages:
chunk 1 went to the new topic, chunk 2 back to the old one.

Now a thread-less message from the creator adopts the new topic while it
arrives within 5 s of the creation or of the previous adopted message; a
stamped message or a longer gap ends the follow. Per-chat FIFO update
processing (PerChatUpdateProcessor) means nothing from this chat lands in
between, so adjacency bought no safety.

Also drops the duplicated identity helpers the mixin redefined from the
adapter and restores the unrelated _cache_dm_topic_from_message move.

Live (real gateway + Telegram stand-in, DM topic mode, production batching):
main misroutes all four cases; the pairing as proposed misroutes the
interleaved-DM and split-opener cases; this lands every case in the new topic,
and a lobby message 7 s later still recovers to the bound topic.
2026-10-19 21:47:53 -07:00
sharpnotebot
7cfafba18e fix(telegram): 建立 topic 時不再快取名稱,恢復自動改名 (Refs #136567)
The forum_topic_created handler cached the user-chosen topic name (e.g.
"New Chat") in _dm_topics. _get_dm_topic_info treats any _dm_topics hit
as an operator-declared topic, so _rename_telegram_topic_for_session_title
silently skipped every dynamically created topic and session-title
auto-rename stopped working.

Keep only the pending-creation record (opener adoption is unchanged) and
leave _dm_topics to operator config. Topics declared in extra.dm_topics
stay protected from auto-rename.

Tests: real PTB creation -> thread-less opener -> runner rename path
renames once; a config-fixed topic is not renamed; a creation stays
pending without populating _dm_topics. The opener test that pinned the
cache side effect now asserts its absence.
2026-10-19 21:47:53 -07:00
sharpnotebot
37ec498ea7 fix(telegram): record topic creations only from authorized humans and consume them once (Refs #136567)
Builds on the salvaged #137348 commits above. The pairing store accepted
any private-chat forum_topic_created service message and kept records
whose opener arrived already threaded until the TTL ran out.

- Record a creation (and cache its topic name) only when the service
  Message carries message_thread_id, has a non-bot sender, and passes
  the existing intake prefilter _is_user_authorized_from_message, so a
  rejected user cannot populate adapter state.
- Cap the store at _NEW_TOPIC_OPENER_MAX_PENDING (256), evicting the
  oldest stamp after the TTL prune.
- The first later message from the same chat and sender consumes the
  record whether it is adopted, already threaded, non-adjacent or
  expired; adoption still requires a thread-less, adjacent, fresh
  opener. Other chats and senders neither adopt nor consume it.

Tests: adds real PTB Update.de_json -> connect() -> process_update
cases for unauthorized, bot, missing thread/sender, healthy consume,
non-adjacent consume, other chat/sender, expiry and the cap. Phase 1
of test_pending_created_topics_stays_bounded now expects the five
healthy records to be consumed (it previously pinned the leak), and an
unused unpacked `delivered` is renamed to satisfy RUF059.

Adapted from a local field-tested patch; the PTB service+opener
pairing design is from #137348 (PRELVAS94), and reading the topic id
from Message.message_thread_id rather than ForumTopicCreated follows
e756b3b in #136581 (liuhao1024).
2026-10-19 21:47:53 -07:00
Pedro Relvas
328b64a9a7 fix(telegram): bound the pending-created-topics cache (Refs #136567)
The _pending_created_topics map grows unboundedly: records whose opener
arrives already threaded (the healthy path) return early before any pop,
and records that simply never get claimed are never revisited. Prune
expired records at record time inside _pending_created_topics_store.

Adds a regression test that demonstrates the leak (10 distinct keys all
survive), the prune (negative TTL evicts all), and the routing contract
(fresh record still claims its opener).

Also cleans stale update receipts in the test's connected() fixture so
the admission controller doesn't drop updates across test runs.
2026-10-19 21:47:53 -07:00
PRELVAS94
3687ef0bf4 fix(telegram): route a new DM topic's thread-less opening message into that topic
Telegram normally stamps a new private-chat topic's opening message with the new
message_thread_id, but it sometimes delivers that opener with no thread id at all.
A forum_topic_created service message carries no text, so no core handler matched it and
the new topic id was never learned: the opener arrived lobby-shaped and gateway topic
recovery (gateway/run_topics.py) pinned it to the most recently bound topic, leaving the
new topic with no session, binding or auto-rename.

- telegram_topic_routing.py: narrow handler for filters.StatusUpdate.FORUM_TOPIC_CREATED
  records (chat_id, sender_id) -> (new thread id, creation message id, stamp) for private
  chats and caches the topic name; the opener adopts that thread id in _build_message_event
  (one-shot, only for the message immediately after the creation, inside a 120s window).
- adapter.py: wire the handler + mixin in, and drop the now-unreachable
  forum_topic_created branch in _resolve_topic_binding.
- tests/plugins/test_telegram_forum_topic_created_opener.py: real PTB dispatch coverage.

Fixes #136567
2026-10-19 21:47:53 -07:00
Teknium
bc3cbd50db fix(image_gen,video_gen): poll the FAL queue every 2 s instead of every 0.1 s (#141368)
fal_client's SyncRequestHandle.get() drains iter_events() at its default
interval=0.1, i.e. a status GET every ~0.3-0.5 s including RTT. Through the
Nous tool gateway (200 requests per fixed one-minute window) a single 12 s
image cost 42 requests (~208 req/min), so a second concurrent job — or the
same user's video job — trips RATE_LIMIT_EXCEEDED on submit, status and
result calls.

Add tools.fal_common.wait_fal_queue_result(): drain iter_events() at
FAL_QUEUE_POLL_SECONDS (2 s), then call get(), whose first status check now
sees Completed and goes straight to the result GET. Public SDK API only, no
monkeypatching. The image tool's interrupt-aware _wait_fal_result and both
FAL video waits (generation + SeedVR upscale) use it.

Live, one gpt-image-2.5 flare image via the gateway: 42 -> 9 requests,
12.1 s -> 12.5 s wall clock.

Test fakes that modelled the handle with only get() gain an empty
iter_events(); two touched test files also get encoding="utf-8" on their
config write_text (windows-footguns).
2026-10-19 01:31:31 -07:00
Teknium
fbd482d5c5 fix(telegram): a newer chunk no longer cancels a committed batch flush
_enqueue_text_event cancels the key's previous flush task on every new chunk,
even after that task has popped its batch and is dispatching it. With
dm_topic_auto_transfer on, a second root-DM message arriving while
createForumTopic for the first was in flight cancelled the dispatch: Telegram
had already created the topic, Hermes lost its ID, and the hold-queue replay of
the still-root message created a second topic, leaving the first empty.

_flush_buffered now leaves the per-key task slot once it pops the batch, so a
newer chunk re-arms a fresh flush instead of cancelling it. Committed flushes
are tracked per (family, key): a later flush for the same key waits for the
earlier one to settle, keeping order. Disconnect teardown still cancels them
(and the cancel path still holds the popped event).

Test: a fake Bot pauses createForumTopic while a second root message arrives;
no event is held, the first keeps topic 777, and every created topic gets its
message.
2026-10-19 01:15:18 -07:00
Teknium
407303dfdc fix(telegram): move dm_topic_auto_transfer to adapter ingress so the reply lands in the new topic
Builds on the salvaged #139188 (@KoNit-K). The salvaged commit ran the transfer in the runner's
_hmwa_resolve_session, which is too late through the real adapter. By then the adapter has keyed
the session on the root-DM source, and _handle_message has already answered with the lobby
reminder. So with the key on, no topic was ever created, and every root-DM message got the
"main chat is reserved" notice.

- The transfer now runs in TelegramAdapter.handle_message before session keying
  (telegram_topic_transfer.py), through a runner hook (_transfer_telegram_root_dm) wired in
  _wire_adapter_handlers next to topic recovery.
- If topic creation fails, the hook returns the lobby-recovery topic (fallback). Commands,
  internal wakes, routed events and unauthorized senders are never moved.
- The first reply in the new topic carries no reply anchor (the root message lives outside the
  topic), via reply_anchor_override="". This replaces the base.py metadata flag.
- With the key unset (default), behaviour is unchanged and the v0.22 lobby recovery stays
  (#136567).
- The top-level `telegram: dm_topic_auto_transfer` YAML key is bridged into extra, like
  disable_topic_auto_rename.
- Documented in the Telegram multi-session docs.

Refs #139136
Refs #134889 (MSG-15)
Refs #141321
2026-10-18 19:27:36 -07:00
David Dudok de Wit
de526521ab fix(gateway): let a serial reader return once a busy burst input is held
Signal and IRC await handle_message before they read their next input.
A busy photo or queue-mode text was held for the burst window and the
call returned only after the durable commit, so the burst's next input
could arrive only once the burst had committed alone: two turns where
main merged one, and the reader stalled about 0.38 s per busy input.

An adapter now declares serial_receive_loop when it delivers a chat's
next input only after handle_message returns and returning triggers no
acknowledgement. For it, dispatch_busy_burst returns as soon as the
input is held, as main returned once the input was merged into the
pending slot. The burst still commits once and in order, and a failed
commit is logged. Every other adapter keeps commit-before-return.

The reader still never runs ahead of what it returned on:
- a command first waits until every earlier input of that reader has
  committed (/stop, /new and /reset drop their own chat's held burst),
  so /restart cannot close admission under a held input and /new
  cannot miss one still committing;
- a chat holds at most one uncommitted burst: the next one waits for
  that commit, as main's reader waited at its first commit.

Flagged: Signal, IRC, email, Matrix, Mattermost, ntfy, Photon, SimpleX,
WeCom, WhatsApp and Feishu. Buzz is left out: it saves its cursor only
after the call returns.

Refs #134889
Fixes #140538

(cherry picked from commit e72e05a1e6e415ff54426b205dcc6b6f408417cf)
2026-10-18 03:15:07 -07:00
kshitijk4poor
793ec8d77d docs(weixin): the connector docstring names both no-bundle cases 2026-10-18 06:04:35 +05:30
Pedro Relvas
e681d6fae5 fix(ssl): route the auth and platform certifi pins through the shared re-derivation
The Nous credential exchange builds its TLS context in
hermes_cli/auth_device_flow._default_verify, which on macOS pinned
certifi.where() directly. That made it a second trust stand outside
agent/ssl_verify, so an install-environment rotation could hand it the
cacert.pem of a deleted environment and every credential refresh failed
until the gateway restarted (#137255, seen in the wild on a launchd
gateway).

_default_verify now asks agent.ssl_verify for the bundle, which
re-derives a path the rotation invalidated. The same one-line move
covers the other three direct certifi.where() consumers — the Weixin
and WeCom aiohttp connectors and the Actual relay's ssl_ca_cert — so
no pin in the tree bypasses the re-derivation.
2026-10-18 06:04:35 +05:30
Pedro Relvas
6bd9c10e32 fix(ssl): re-resolve certifi's CA bundle after an install-environment rotation
A process that imported certifi before the package manager replaced its install
environment keeps the deleted directory in `certifi.where()` for the rest of its
life: the path is derived from the imported module's `__file__` and nothing
re-derives it. httpx builds every SSL context through that path, so
`httpx.Client(verify=True)` raises FileNotFoundError at construction — the
OpenAI-compatible client factory turns that into `RuntimeError: Failed to
initialize OpenAI client: [Errno 2] No such file or directory`, and every TLS
tool that process owns fails until it restarts. `requests` fails one step
further out: its DEFAULT_CA_BUNDLE_PATH is a string frozen when requests is
imported, so a rotated environment leaves every call raising `OSError: Could not
find a suitable TLS CA certificate bundle`.

- agent/ssl_verify.py: certifi_bundle_path() re-executes the imported certifi
  module against the live sys.path when its bundle is gone, logs one WARNING
  naming the dead path and the recovered one, and reports None when there is
  nothing to re-resolve. resolve_httpx_verify() hands the platform context over
  in that case instead of the bare `True` httpx would resolve through the dead
  path; requests_verify() gives requests call sites a bundle that exists now.
- plugins/browser/_common.py, plugins/web/keenable/provider.py: pass that bundle
  to the two requests call sites that inherit requests' frozen default.
- tests/agent/test_ssl_verify.py: the rotation is simulated by importing certifi
  from a stand-in environment, deleting its directory and then building a client
  (no package manager involved).
2026-10-18 06:04:35 +05:30
Teknium
952666501f feat(setup): public names for the gateway setup-wizard helpers
Platform setup_fn code (bundled QQ Bot, Weixin, Signal and the community QQ
plugin) imported _print_setup_header, _confirm_reconfigure,
_offer_home_channel, _save_env_values and _prompt_csv from
hermes_cli.gateway_setup_wizard. They are now print_setup_header,
confirm_reconfigure, offer_home_channel, save_env_values and prompt_csv; every
internal caller moves (no aliases). Bundled QQ setup drops the private _gw()
facade for hermes_cli.setup / cli_output / config primitives.
2026-10-17 14:51:46 -07:00
Teknium
914737a811 feat(gateway): public SSRF-safe HTTP client helper for platform plugins
Every bundled adapter built its client from three private pieces:
gateway.platforms.base._ssrf_redirect_guard, tools.url_safety's
create_ssrf_safe_async_client and _http_client_limits.platform_httpx_limits.
The redirect guard becomes public (ssrf_redirect_guard; callers renamed, no
alias) and gateway.platforms.helpers.platform_http_client(**kw) composes all
three, with the guard ahead of any caller response hooks. QQ Bot and WeCom
move to it.
2026-10-17 14:51:46 -07:00
Teknium
53de7ff326 feat(clarify): public get_pending() query replaces _lock/_entries reads
Adapters rendering native clarify buttons (core Discord/Telegram, base
send_clarify, the community QQ plugin) read tools.clarify_gateway._entries
under _lock to learn whether a request is still pending and its choices.
get_pending(clarify_id) returns the entry while it awaits an answer, else
None; internal readers move to it.
2026-10-17 14:51:46 -07:00
Teknium
47d9efe490 feat(gateway): plugin platforms declare group-chat allowlist and pairing suppression
Two authz behaviours were hard-coded on Platform.QQBOT/TELEGRAM/... in
gateway/authz_mixin.py (_GROUP_CHAT_ENV, _ALLOWLIST_SUPPRESSES_PAIRING), so a
plugin-registered platform could not get them and removing the bundled QQ
adapter would silently drop QQ_GROUP_ALLOWED_USERS gating and change pairing.

PlatformEntry gains group_allowed_chats_env and allowlist_suppresses_pairing;
authz_mixin reads them through authz_field (live entry, else the bundled
gateway_env.AUTHZ). Every bundled platform that was in the old tables declares
them in its AUTHZ, so behaviour is unchanged.
2026-10-17 14:51:46 -07:00
unsupportedpastels
419e6627aa fix(memory): serve a memory provider only to the profile it was initialized for
On a multiplexed gateway every served profile's agents share one process.
Each agent's MemoryManager owns its own provider instance, but nothing stopped
a tool call or lifecycle hook from another profile's context, or from a
context naming no profile, from reaching it. Nothing stopped two agents being
handed one shared instance either. The in-repo providers also bound their
stores from the ambient home rather than the one the manager passed.

MemoryManager.initialize_all records the profile home (and agent_identity) it
bound its providers to. Then:

- Tool calls and every lifecycle hook (prefetch, queue_prefetch, sync_turn,
  on_turn_start, on_memory_write, on_session_end, on_session_switch, the
  session boundary, on_pre_compress, on_delegation) run only when the caller
  explicitly names that profile: the context's HERMES_HOME override, or the
  home its secret scope was built for. On a multiplexed process a caller that
  names no profile is refused, never resolved to the process's own profile.
  A refused checkpoint compression raises, so the transcript stays
  uncompressed.
- Background hooks run under the owning profile's HERMES_HOME, set
  explicitly in the worker.
- An instance another profile's manager already bound is dropped, not
  re-initialized (logged as memory_provider_instance_shared). Claims are
  tracked by instance identity, never by the provider's own hash or
  equality; on a multiplexed process an instance that can't be tracked
  (no weak reference) is refused too.
- handle_tool_call passes hermes_home / agent_identity next to the previous
  commit's caller_gsk. A provider with the two-argument handle_tool_call gets
  only what it declares; caller_gsk alone made every call to it a TypeError.
- The model sees a generic "refused, check gateway.log". gateway.log keeps
  memory_caller_profile_unresolved and both homes.

ByteRover and RetainDB now bind their store from initialize()'s hermes_home.
Both already kept their bindings on the instance and hold no profile state at
module level.

The provider side of the rule is documented on MemoryProvider and in the
memory-provider plugin guide: a new instance per load, every binding from
initialize()'s hermes_home, no profile state at module or class level, no
per-call rebinding. Core cannot see inside an external provider; one that
keeps a process-wide binding still mixes profiles' memories.

The previous commit's two MagicMock tests in test_run_agent.py move into
tests/agent/test_memory_provider_caller_profile.py (test_run_agent.py is over
its line cap and may not grow). That file drives both dispatch paths and
every hook with real managers and two profiles interleaving on threads;
tests/plugins/memory/test_provider_multiplex_contract.py does the same for
ByteRover and RetainDB with a fake backend.

Refs #134889 (PLG-11)
Refs #140208
Refs #140058
2026-10-17 13:28:18 -04:00
unsupportedpastels
5ec9bb6b10 fix(google-chat): answer a parked-profile HTTP event retryably
Google Chat's HTTP callback awaits the dispatch before it answers, so
unlike Pub/Sub (acked on hand-off) the delivery is not acknowledged yet.
The parked-profile refusal still answered HTTP 200 with nothing
admitted, and the message id stayed in the adapter's dedup cache, so
Google had no reason to retry and a manual resend would be the only way
back.

dispatch_http_event now runs the dispatch inside
parked_route_refusal.retryable_ingress(). Inside that scope,
drop_rejected_route records the refusal instead of sending an in-chat
notice. The adapter then releases what ingress recorded for the
unadmitted delivery (its dedup claim and the DM thread count) and raises
the named ParkedRouteRefused, which the platform-event callback answers
as 503 profile_parked with Retry-After. _dispatch_message swallows
exceptions, so the refusal is carried by the scope, not raised from the
shared helper. Pub/Sub keeps the in-chat notice.

A redelivery of the same event after the profile is served again is
admitted exactly once, and reads its DM thread as the first delivery.

Refs #134889 (GW-12)
Refs #140018
2026-10-17 13:16:34 -04:00
Teknium
861a0299ed refactor(gateway): no re-export shims for the split status/base helpers; the lock split is one-way
The round-1 health offset moved safe_url_for_log and the scoped-lock
release pair into siblings but re-exported them from gateway.status /
gateway.platforms.base, and status_scoped_locks read gateway.status
privates at call time while gateway.status re-exported the sibling's
privates (_unusable_lock_dir, _warned_unusable_lock_dirs). AGENTS.md:
no re-export shims for internal moves.

- gateway/status_lock_dir.py: the unusable-lock-dir report
  (ScopedLockDirUnusable + public unusable_lock_dir / _recovered /
  reset / reported). gateway.status imports it; it imports nothing back.
- gateway/status_scoped_locks.py: only the release pair, reading
  gateway.status at call time; gateway.status no longer imports it.
- Every importer points at the real home: base.py, run_bootstrap.py,
  the Feishu and Slack adapters, and the tests that patch them
  (gateway.status_scoped_locks.release_*). safe_url_for_log comes from
  gateway.platforms.base_log_safety; base.py imports it only for its
  own use.
- classify_changes: status_lock_dir.py rides with gateway/status.py on
  the e2e_upgrade lane.

code_health: 0 blocking (status.py stays under its main value).

Review finding by @unsupportedpastels on #140490 (minor 4) and by
@alt-glitch on #140490 (suggestion 4)
Refs #134889 (W2)
Refs #140337
2026-10-17 08:03:53 -07:00
Teknium
b490ef0c5b Merge pull request #140186 from NousResearch/fix/pkg7-bots-multiplex
fix(gateway): multiplexed WhatsApp TIME-WAIT, Feishu comment scope, Discord voice, webhook cron profile (package 7, MSG-16, MSG-13, MSG-14, CRON-2)
2026-10-16 21:11:47 -07:00
Teknium
c05c476f14 refactor(telegram): move the reply-anchor normaliser into telegram_ids
The salvaged #139642 normaliser grew adapter.py past its code-health
cap. It is a pure id helper, so it lives beside normalize_telegram_chat_id
as parse_telegram_message_id; behaviour is unchanged.

Refs #139611
Refs #134889 (MSG-17)
Refs #140138
2026-10-16 20:25:09 -07:00
PRATHAMESH75
29cda7a5ef fix(telegram): send unanchored when a reply anchor is not a message id (#139611)
Route wakes (kanban-wake, loop-tick) are admitted with a synthetic JSON
identity (session_automation.admit_route_wake), and
_reply_anchor_for_event passes it to the send as the reply anchor. The
Telegram adapter ran raw int() on that anchor in
_metadata_reply_to_message_id, _reply_to_message_id_for_send and
_chunk_reply_routing, so every reply into the session failed with
"invalid literal for int() with base 10: '["kanban-wake",...]'" and
the poisoned anchor was retried.

All three sites now go through _telegram_message_id(): a non-numeric
anchor is not a Telegram message id, so the reply is sent unanchored,
or on the DM topic's own metadata anchor when there is one. The
normaliser follows luyifan's approach in #72937, which no longer applies
after the adapter refactor.

Co-authored-by: luyifan <al3060388206@gmail.com>
(cherry picked from commit 5b9f0d6cea2896c82e882297a0cd5e92571fdbb8)
2026-10-16 20:24:24 -07:00
Teknium
fb5e7b6143 docs(platforms): adding-a-platform guides point at the plugin declarations
The env bridge, allowlist names and prompt hint now live on the PlatformEntry (gateway_env.py,
AUTHZ, platform_hint), not in _ENV_STEPS, _PLATFORM_ALLOWLIST_ENV or PLATFORM_HINTS.
2026-10-16 19:42:34 -07:00
Teknium
b95c4861b2 fix(platforms): bundled authorization env names hold when the live entry lacks them
Independent review found the allowlist, the open-policy startup refusal, the pairing-noise
rule and `hermes pairing revoke` reading only the live PlatformEntry: a user plugin overriding a
bundled platform without the fields, safe mode or a disabled plugin then gated on nothing
(looser than main, whose core tables always applied).

Each bundled plugin now declares them once as `gateway_env.AUTHZ` (passed to register() with
**), and `gateway.platform_env.authz_field` answers from the entry, else from that file (read
without the plugin package). Probed main vs head: 208/208 authz decisions identical in normal,
safe-mode, plugin-disabled and user-override modes; revoke drops the user in all four.

The terminal secret blocklist and config_env_table_keys() read the same files, which removes the
three hand-listed plugin secrets in local_env_policy.
2026-10-16 19:42:34 -07:00
Teknium
b035c13e77 fix(platforms): plugin-declared rows reach callers that run before or outside discovery
CI found three paths that read the registry where core used to read its own table:
- the system prompt's platform hint was built before any discovery (direct builders):
  discover on a miss, like the send and config lookups already do;
- the dashboard's auth-posture check resolved the allowlist env inside the profile scope,
  whose registry overlay may not hold the entry: resolve it in the request scope, the way
  _env_value_rules already does;
- a parked profile's config read suppresses plugin discovery by design (#123386), so its
  bundled-platform env rows vanished and the duplicate-credential guard stopped seeing a
  shared bot token. Bundled rows are now read straight from plugins/platforms/<p>/gateway_env.py
  (core-only imports, never the plugin package or register()) whenever the registry has no
  entry: suppressed discovery, safe mode, a disabled plugin. That is main's behaviour.

Buzz's test loader imports adapter.py as a bare module, so its sibling imports go through the
existing loader-agnostic helper (generalized from nostr_auth).
2026-10-16 19:42:34 -07:00
Teknium
2f4b42191e fix(platforms): import new plugin siblings relatively (no second adapter copy)
The plugin loader runs a bundled platform package as hermes_plugins.platforms__<name>.
An absolute `from plugins.platforms.<name>.<sibling> import ...` inside register() imports
the canonical package too, whose __init__ loads a second copy of the adapter. The prompt-hint
and send-target siblings added on this branch did that for buzz, feishu and slack (three new
double-loaded adapters vs main). Relative imports, as the dashboard_card / gateway_env siblings
already use; after every plugin registers, the double-loaded set is back to main's five.
2026-10-16 19:42:34 -07:00
Teknium
3c3f85a0d0 refactor(gateway): plugin platforms declare their env->config rows on PlatformEntry
Move the per-platform `_Cred` rows of `_ENV_STEPS`, their helper steps and the
`_ENV_ENABLE_CREDENTIALS` rows for every plugin-backed platform (telegram, discord,
slack, whatsapp, whatsapp_cloud, signal, mattermost, matrix, email, sms, dingtalk,
feishu, wecom, wecom_callback, weixin, bluebubbles, qqbot, yuanbao) out of
gateway/config_env.py into each plugin's `gateway_env.py`, attached via two new
PlatformEntry fields: `env_overrides` (ordered steps) and `env_enable_credentials`.

`gateway/platform_env.py` holds the declarative `EnvCred` row and shared parsers.
`_apply_env_overrides` runs the rows of entries with activation evidence (same gate
as the plugin enable pass, computed once). Core-only rows (api_server, webhook,
msgraph_webhook, relay) stay in config_env. profile_channels reads the rows from
registry entries; the import-time terminal secret blocklist lists the three secrets
only those rows read, pinned by a new invariant test.

Resulting GatewayConfig and explicit-disable warnings are identical (differential
oracle, 100 fixtures); only env-created insertion order of api_server/webhook/
msgraph_webhook relative to plugin platforms changes.
2026-10-16 19:42:34 -07:00
Teknium
28e4da48fe refactor(dashboard): channel cards and env-value checks read the plugin's PlatformEntry
The Channels page catalog (_PLATFORM_OVERRIDES) and the PUT env-value validators
(_ENV_VALUE_RULES) duplicated per-platform data the bundled platform plugins can
declare. Each plugin now declares its card on its PlatformEntry (new dashboard
block: dashboard_label, dashboard_description, docs_url, dashboard_env_vars,
dashboard_required_env, env_value_rules); core keeps static rows only for the
core-only platforms (api_server, webhook, msgraph_webhook, relay).

Telegram/Slack validators move into their plugins. The PUT route resolves the
rules right after _require_platform (catalog build already materialized every
entry, so nothing extra is imported) and before entering _profile_scope, where
the registry's profile overlay may not hold the entry.

Adapters over their size cap (discord, feishu, matrix, slack, telegram) keep the
card in a sibling dashboard_card.py, imported relatively so no second canonical
copy of the adapter module loads; surplus blank lines offset the two added lines.

Behaviour identity: differential oracle over the real route handlers (GET
/api/messaging/platforms root + profile, PUT valid/invalid per rule root +
profile) is byte-identical to base.
2026-10-16 19:42:34 -07:00
Teknium
e24f12c69f refactor(send): read send_message target syntax and standalone routing from the plugin registry
Delete the per-platform tables in tools/send_message_targets.py (_PLATFORM_PARSERS, 14 rows) and
tools/send_message_tool.py (_PLUGIN_STANDALONE_MEDIA, _TEXT_SENDERS, plus the discord-always and
whatsapp-mentions ladders). Each bundled plugin now declares them on its PlatformEntry:

- target_ref_syntax_fn: the old parser, body unchanged. A new field rather than parse_target_ref_fn
  because that field is an authority (strict under pass_unresolved_references, no "not explicit"
  sentinel, not re-applied to channel-directory hits) and reusing it would change react/cron
  behaviour for ntfy/buzz/photon.
- standalone_send: StandaloneSendPolicy (label, media, all_sends, captionable,
  empty_list_between_chunks, forward_force_document, mentions, text_direct).

Shared builders and the NOT_EXPLICIT sentinel live in gateway/platforms/send_targets.py so plugins
import no core-private helpers. Lookups discover plugins first when the name is not registered yet
(fresh CLI/cron process). Differential oracle (33 platforms x 48 refs, 10 send cases each): base and
head output identical.
2026-10-16 19:42:34 -07:00
Teknium
3d21ec1294 refactor(platforms): plugin PlatformEntry carries its prompt hint and display defaults
PLATFORM_HINTS (agent/prompt_builder.py) and _PLATFORM_DEFAULTS (gateway/display_config.py)
duplicated per-platform data for every bundled messaging plugin. Both consumers already fell
back to the registry (PlatformEntry.platform_hint / display_tier), so the plugin rows move onto
each plugin's register() call and the core tables keep only core surfaces (cron, cli, tui,
desktop, api_server hints; webhook, api_server display rows).

New PlatformEntry field display_overrides: per-key defaults layered over display_tier (telegram,
discord, slack, wecom had tier + tweaks). Hint text is copied byte-for-byte (the shared
_MEDIA_NATIVE fragment is inlined); a base-vs-head oracle of platform_hint() and
resolve_display_setting()/resolve_tool_progress() for every platform, with and without user
display overrides, is byte-identical. Oversize adapters keep the hint in adapter_hint.py.
2026-10-16 19:42:34 -07:00
Teknium
2ab1a408d0 refactor(gateway): bot-bypass and own-policy startup gates read the PlatformEntry
_ALLOW_BOTS_ENV (authz_mixin) and _OWN_POLICY_OPEN_ENV (run) duplicated data the
platform plugins own. PlatformEntry gains allow_bots_env and own_policy_env; the
discord/feishu/telegram/slack and wecom/weixin/yuanbao/qqbot/whatsapp plugins
declare them and both tables are deleted.

Both consumers run an idempotent discover_plugins() first so a hand-built config
or bare runner still sees the entries. The bot bypass fails closed with no entry.
The open-policy startup check fails closed for a bundled platform whose plugin is
disabled or failed to load (conventional <NAME>_* names, manifest-declared
allow-all): config can still enable such a platform, and a later plugin enable
re-wires its adapter without re-running the startup check.

_own_policy_envs lives in run_startup.py to keep run.py under its line cap;
small offsets in the discord/slack/feishu/telegram plugin files for the same reason.
2026-10-16 19:42:34 -07:00
Teknium
0663bdf98c refactor(platforms): read connected checks, allowlist env, cron home vars and status labels from the plugin registry
Delete the hand-written per-platform rows that duplicated data every bundled
platform plugin already declares on its PlatformEntry:

- gateway/config.py `_PLATFORM_CONNECTED_CHECKERS`: the weixin, whatsapp_cloud,
  signal, bluebubbles, qqbot and yuanbao rows move to a new narrow
  `PlatformEntry.config_connected_fn` (verdict from the merged PlatformConfig
  alone, no env fallback, owns the token shortcut so Weixin can refuse a bare
  token). Core-only rows (api_server, webhook, msgraph_webhook, relay) stay.
- gateway/pairing.py `_PLATFORM_ALLOWLIST_ENV` and the derived authz maps
  `_ALLOWED_USERS_ENV` / `_ALLOW_ALL_ENV`: read `allowed_users_env` /
  `allow_all_env` (discovering plugins first). The unauthorized-DM
  "allowlist set -> ignore" default keeps its historical platform set as a
  names-only frozenset so irc/teams/... DM behaviour does not change.
- cron `_HOME_TARGET_ENV_VARS`: env var from `cron_deliver_env_var`; the
  origin-fallback / deliver=all order is kept as a names-only priority tuple.
  `_KNOWN_DELIVERY_PLATFORMS` keeps only webhook and wecom_callback (no cron var).
- hermes status `_PLATFORM_LABELS`: plugin labels already overrode every row;
  discover first and use them alone.
- dashboard `_platform_authz_env_names` drops its read of the pairing table.

Differential oracle (connected matrix, pairing/dashboard env lookup,
_is_user_authorized + unauthorized-DM matrix, cron known/home/resolve/all,
hermes status platform section, hermes dump) is identical on base and head.
2026-10-16 19:42:34 -07:00
Teknium
4b17231b53 fix(feishu): an unscoped comment from a secondary adapter fails closed
handle_drive_comment_event bound the launch profile scope to ANY unscoped
callback. Every secondary path arrives scoped today, but a secondary that lost
its context would quietly run its comment turn on the launch profile's
credentials, where main raised UnscopedSecretError. The adapter now passes
secondary (it has a multiplex owner profile), and only the launch adapter may
borrow the launch scope; a secondary's unscoped event is dropped with a warning.

Tests: test_an_unscoped_comment_from_a_secondary_adapter_fails_closed and
test_the_adapter_tells_the_comment_handler_whether_it_is_a_secondary (red
before, green after).

Review finding by @unsupportedpastels on #140186
Refs #134889 (MSG-13)
2026-10-16 19:24:58 -07:00
Teknium
7d9f04469b docs(whatsapp): state port_is_free's REUSEADDR contract
With SO_REUSEADDR a TIME-WAIT-only port reads as free on Linux. That matches the
Node bridge, which sets the same option, and the bridge allocator and ownership
check in this module are the only callers (git grep). The docstring now says so
and warns against gating a non-REUSEADDR binder on it.

Review finding on #140186 (independent review)
Refs #134889 (MSG-16)
2026-10-16 19:21:37 -07:00
KoNit-K
c7ae28da71 fix(feishu): scope default comment agent turns
(cherry picked from commit 71ae9558798c8f6c4900485dd9d7c7084447511c)
2026-10-16 19:21:04 -07:00
Teknium
1848982075 fix(whatsapp): POSIX-only reuse in the probe, real TIME-WAIT test
On top of the salvaged SO_REUSEADDR probe: set the option only on POSIX
(libuv does the same; on Windows it lets a bind share a live listener's
port, which would read another profile's bridge as free), and pin the
restart case with a real kernel TIME-WAIT entry instead of a socket mock,
plus a live listener on the same port still failing closed.

Pre-existing before #106742 (bridge_ownership.py is unchanged since
d385b01469, an ancestor of d04056d609); only multiplexed secondaries
reach this check. Needs a live retest with a paired WhatsApp secondary
and `systemctl --user restart hermes-gateway`.

Refs #139425
Refs #134889 (MSG-16)
Refs #140138
2026-10-16 19:21:03 -07:00
KoNit-K
155588754a fix(whatsapp): reuse bridge ports after restart
(cherry picked from commit cb1eee70fa9abbefe9f4ba300d1a96025266c9c2)
2026-10-16 19:21:03 -07:00
Teknium
f41ac07695 fix(slack): early auth reject checks the session thread's routed profile
_early_reject_unauthorized dropped the decoded thread_id, so a thread-scoped
profile_routes entry checked the default profile's pairing store: a caller
approved only in the routed profile had slash commands (even /stop) and
messages in that thread dropped. Pass thread_id from both the slash and the
message path to _is_sender_authorized and the build_source fallback.
2026-10-16 14:22:13 -07:00
Teknium
0815b4ed4a fix(slack): concurrent slash commands of one session reach the gateway in arrival order
Names resolved for a slash turn are awaited before the handoff and Bolt runs
callbacks concurrently, so a /queue whose cold users.info answered late
reached the gateway FIFO after a later one. A slash now reserves its
session's slot before any lookup and hands over only after the slash ahead
returned from handle_message; a slash cancelled while waiting still chains
the one behind it. /stop, /approve, /deny, /pause take no slot.

Ported from #128722 (9b719083, eb546b6a) into adapter_slash_lane.py.

Co-authored-by: John Paul Soliva <soliva.johnpaul@icloud.com>
2026-10-16 14:22:13 -07:00
Teknium
a7010c4913 refactor(slack): slash payload decoding lives in adapter_slash_payload
Move the two pure slash-payload helpers (gateway text, thread anchor) out of
the adapter facade so the slash-turn parity fix keeps adapter.py under its
health cap. No behaviour change.
2026-10-16 14:22:13 -07:00
Teknium
e817ac8c8e fix(slack): /pause is handed over before any Slack lookup
/pause engages the emergency stop and starts no turn, like /stop and /approve,
so a cold users.info must not hold it back. Ported from 9b719083 in #128722
(its arrival-order handoff lane is left out).

Co-authored-by: John Paul Soliva <soliva.johnpaul@icloud.com>
2026-10-16 14:22:13 -07:00
John Paul Soliva
d2ac28c77d fix(slack): a slash command that stops or unblocks the running turn waits for no Slack lookup
The names the slash path resolves (users.info, conversations.info) were awaited
before the event reached the active-session dispatcher. With a shared channel
session, a second operator's /stop sat behind their uncached users.info while
the first operator's worker kept running.

/stop, /new, /reset (the interrupt-then-dispatch commands) and /approve, /deny
start no turn of their own, so they are handed over before any lookup. Commands
that do start a turn (/queue, /retry, /goal, ...) and free-form questions keep
the names and the channel prompt.
2026-10-16 14:22:13 -07:00
John Paul Soliva
bda86e96f6 fix(slack): a rejected slash-command sender costs no Slack lookup
The message path rejects an unauthorized sender before any lookup (5bb933eedf); the slash path now resolves the channel and user name, so a sender the gateway was going to reject cost a conversations.info and a users.info first. Ask the same early gate before resolving. In a channel the runner only drops such a sender, so stop there. In a DM it answers per unauthorized_dm_behavior (pairing code or decline), so the event still reaches it, without names, exactly as before this branch.

Docs: N/A, slack.md already says an unauthorized DM gets the pairing prompt.
2026-10-16 14:22:13 -07:00
John Paul Soliva
c1c2bab742 fix(slack): load channel skill bindings on slash-command turns
`/hermes <question>` can open a new session, and bound skills load only
when a session starts. The slash event carried no auto_skill, so a session
opened that way never loaded the channel's slack.channel_skill_bindings,
unlike one opened by an ordinary message. Resolve it the same way the
message path does.
2026-10-16 14:22:13 -07:00
John Paul Soliva
1424ffa429 fix(slack): carry channel prompt and source names on slash-command turns
_handle_slash_command built its MessageEvent without channel_prompt and its
source without chat_name/user_name, unlike the message path. A /hermes turn
ran without the configured channel_prompts and the bot identity line, and as
a human turn it re-pinned channel_pin to None and re-keyed the pinned
session-context prompt; the next ordinary message flipped both back, so every
slash turn cost two agent rebuilds and two prompt-cache misses. Synthetic
events copied from it (/retry, /queue, /steer fallback, /goal kickoff)
inherited the gap.

Resolve the names and the channel prompt with the same helpers the message
path uses.
2026-10-16 14:22:13 -07:00
Maciej Lisiewski
428f2e0202 fix(deps): bump @grpc/grpc-js 1.14.4 → 1.14.6 in photon sidecar (high, GHSA-482/481)
Latest 1.14.x release older than 3 days; clears the 1.14.5 floor.
2026-10-16 17:26:41 +02:00
Maciej Lisiewski
4bcf60191a fix(deps): bump undici 7.29.0 → 7.30.0 in photon sidecar (high, GHSA undici alerts)
7.30.1 is < 3 days old, so pin the override at 7.30.0 — the latest
release older than 3 days that clears the 7.29.1 floor.
2026-10-16 17:26:35 +02:00
Teknium
42762d6a64 refactor(signal): plugin wiring lives in register.py, like QQ Bot and Yuanbao
The registration hooks had grown the moved adapter past 1,000 lines and put
two forward-only wrappers next to the message code. register.py now holds
the configured/validate checks and register(), and registers the setup and
standalone-sender functions directly. adapter.py is back to 983 lines; no
behaviour change (composite live probe matches main).

Addresses the Greptile finding on this PR.
2026-10-16 07:09:45 -07:00