Commit Graph

3963 Commits

Author SHA1 Message Date
Teknium
85af8f2102 fix(dashboard-auth): a refused JWKS fetch is not repeated on every request
PyJWKClient caches only a successful key fetch. While a firewall refused
the Portal's /.well-known/jwks.json (403, x-vercel-mitigated: deny), every
bearer request on the gateway (iOS app, Webapp, live voice) and the
dashboard fetched it again: one refused lookup per request, which keeps
such a block in place.

make_jwks_client (used by the nous and self-hosted providers) now returns
a PyJWKClient whose fetch_data, after a failed fetch, answers the same
PyJWKClientConnectionError from memory for JWKS_FAILURE_BACKOFF_SECONDS
(30 s) instead of hitting the network. The result is unchanged
(ProviderError -> 503, never a forced logout); the first request after the
window fetches again, so sign-in recovers on its own.

Part of #160843.
2026-12-01 13:24:34 -08:00
Teknium
4440b3e345 fix(windows): owned children never break away; detached spawns share one breakaway-denied retry
The WhatsApp bridge is an owned child (spawn_owned): it must not outlive its gateway. It was
spawned with CREATE_BREAKAWAY_FROM_JOB, so a gateway in a job that forbids breakaway (Desktop, an
IDE or agent host, Task Scheduler) could never start it (WinError 5 on every reconnect), and under
a job that allows breakaway it escaped that job's teardown, keeping the port and the WhatsApp
session. spawn_owned now strips the breakaway bit on Windows, so every owned child stays in its
owner's jobs (the pairing bridge already spawned that way).

Children that must outlive their parent go through one primitive, _subprocess_compat.popen_detached:
breakaway when the parent allows it, else retry inside the job on ERROR_ACCESS_DENIED only. The two
Windows detached spawns without that retry (gateway /update, the Desktop launch) and five copies of
it (default plugins, commit-graph refresh, scratch prune, hermes desktop, launchd fallback) use it.

Fixes #68128

Co-authored-by: morkalg <20704953+morkalg@users.noreply.github.com>
Co-authored-by: IzzyWizzy666 <25311408+IzzyWizzy666@users.noreply.github.com>
Co-authored-by: liuhao1024 <sunsky.lau@gmail.com>
Co-authored-by: Rickard Robin <rickard@kumobits.com>
2026-12-01 13:20:40 -08:00
Teknium
833ea0006e fix(dashboard-auth): an out-of-range scrypt parameter declines the basic provider instead of failing its load 2026-12-01 13:12:30 -08:00
Teknium
e9549fe604 fix(dashboard-auth): a hash whose scrypt parameters exceed the verifier's memory cap declines too
validate_password_hash now runs one derivation under the same maxmem=0 limit the
login verify uses, so a well-formed hash this runtime cannot derive (n=2**15, r=8
on OpenSSL's default 32 MiB cap) is refused at load instead of registering a login
every password fails. Answers the review thread on #162263.
2026-12-01 13:12:30 -08:00
Teknium
de1900473b fix(dashboard-auth): one hash parser for verify and load, reason names the hash's source
The load-time check now uses the same parse as the login verify, so a hash is
refused at load exactly when no password could ever verify against it (main's
lenient base64 decode kept, so no hash that signs in today is newly refused).
The skip reason names the env var when HERMES_DASHBOARD_BASIC_AUTH_PASSWORD_HASH
supplied the hash, since that override wins over config.yaml.
2026-12-01 13:12:30 -08:00
Hukla
0ffedc39ef fix(dashboard-auth): reject malformed basic auth hashes at provider load
Preserve provider-load validation and regression coverage on the current main branch.
2026-12-01 13:12:30 -08:00
alt-glitch
ea4f672368 refactor(terminal): the process registry, terminal config and sudo move from tools/ to terminal_backends/
The 21 flat files that serve the terminal backends join the package:
the process registry and its nine parts, the environment-variable
passthrough, credential file mounts, workspace path resolution, the PTY
query responder, the terminal scope, and the backend table, config,
lifecycle, macOS open rewrite, sudo and sudo askpass of the terminal
tool. file_tools_paths becomes workspace_paths and the terminal_tool_
prefix drops (terminal_tool_backends becomes backends, and so on); every
other file keeps its stem. Function bodies are unchanged; only imports
and module-name strings follow the move. 22 tests move to
tests/terminal_backends/.

Ten old module names keep a generated old-path file and a compat key:
a session started on an older release imports them lazily after an
update from code it has already loaded (the gateway's process notices
and inbound media, an agent's next terminal command, sudo prompt or PTY
process). Each key also binds the module such a session holds to its new
name, so the process table, the sudo password cache and the registered
passthrough variables stay one object. The pinned catalog plugins'
modules are listed in the plugin guide.
2026-12-01 19:40:47 +05:30
alt-glitch
b85ac0f579 refactor(terminal): the terminal backends move from tools/environments/ to terminal_backends/
The terminal backends and their support files leave tools/, which holds
model tools, for a new root package terminal_backends/. base.py becomes
environment.py and its base_* siblings become environment_*;
sandbox_scope.py becomes hosted_scope.py and sandbox_conformance.py
becomes conformance.py. Every other file keeps its stem. Function bodies
are unchanged; only imports and module-name strings follow the move.

tools.environments, tools.environments.local, tools.environments.base
and tools.environments.sudo_password_note keep generated old-path files:
old releases import the first two after an update, an agent process
started on v0.23.2 to v0.23.5 imports the last on its next terminal
command, and the plugin API publishes BaseEnvironment under both
package names. tools.environments.base_output is a compat key for pinned
catalog plugins. terminal_backends joins the tools log component, the
known logger roots and every hand-written package list.

The package is not named sandboxes: on an install whose checkout is
HERMES_HOME that folder holds live sandbox workspaces, and the updater
of a released version deletes or stashes them when a tracked package of
the same name arrives.
2026-12-01 17:49:22 +05:30
alt-glitch
2115d74421 refactor(bots): Bot Mode and Bot Desktop move from tools/ to bots/
tools/ holds model tools. These 19 files register none: they resolve the
Bot Mode roster, deliver message_agent's DMs and run their by-path runner,
hold the cross-connection relay and its receipts, and run the Bot Desktop
screen. They move to a new root package, bots/ (flat plus bots/desktop/,
with the launcher and wallpaper beside the runtime that reads them).
tools/message_agent_tool.py stays; only its imports change.

Function bodies are unchanged and every import stays where it was. Tests
whose subject is a moved file go to tests/bots/, whose conftest imports
the tests/tools/ autouse fixtures they ran under. Loggers follow their
modules; bots joins the tools log component, so `hermes logs --component
tools` shows the same lines, and every hand-written root-package list.

Old names keep working. Each moved top-level module has a MOVES key.
Processes started on v0.21.6 to v0.23.5 that outlive an update import
these modules inside functions and start tools/bot_mode_dm.py by path as
the DM runner, so those names get generated old-path files. Pinned catalog
plugins import tools.bot_desktop and tools.bot_live_delivery; the plugin
guide lists both.
2026-12-01 17:49:22 +05:30
alt-glitch
074383f218 refactor(approval): the approval gate, detection and human prompts move from tools/ to approval/
tools/ holds model tools. These 36 files register none: they decide whether
a command or a write may run, detect dangerous commands, and ask a person
(approval prompts, gateway clarify, slash confirmations). They move to a new
root package, approval/, with command detection in approval/detection/.
tools/approval.py becomes approval/gate.py and tools/approval_detection.py
becomes approval/detection/patterns.py; the other files drop the approval_
prefix or keep their stem. 79 tests whose subject is a moved file move to
tests/approval/, whose conftest.py imports the autouse fixtures of
tests/tools/conftest.py they ran under.

Function bodies are unchanged and every import stays where it was. Loggers
follow their modules: the five module loggers that logged as tools.approval
now log as approval.gate, and approval joins the tools entry of
hermes_logging.COMPONENT_PREFIXES, so `hermes logs --component tools` shows
the same lines. approval also joins packages.find, FIRST_PARTY_MODULE_ROOTS,
_KNOWN_LOGGER_ROOTS, the plugin isolation audit, six check scripts, the P33
profile-scope pattern and the test fixtures that list root packages.

Ten old names keep a file at the old path, each a MOVES key, a
REQUIRED_NAMES row and a file written by scripts/move/generate_shims.py:
tools.approval and tools.clarify_gateway are on the published plugin API,
and all ten are imported inside functions on every turn, message, tool call
or human prompt by a process started on a release up to v0.23.5, which
keeps running its old code after an update swaps the checkout. Five more
modules that pinned catalog plugins import keep their old name through a
MOVES key with no file, listed in the plugin guide.

Both new packages call rebind_loaded_modules from their __init__, so a
session that outlives the update keeps the one gate it already holds: a
notifier registered before the update still reaches a background child's
approval request.
2026-12-01 17:49:22 +05:30
Teknium
da69ea7f26 fix(matrix): pick the E2EE extra by the mode the adapter connects with
Independent review round 2: the updater and the registry hooks resolved the
Matrix E2EE mode from the environment alone, while the adapter resolves it
from its PlatformConfig (config.yaml + env overrides). A profile with
`platforms.matrix.e2ee_mode: off` and a stray `MATRIX_E2EE_MODE=required`
in the process env connected without E2EE, yet `hermes update` requested
`[matrix-e2ee]` (a python-olm build) and the dependency gate stayed false;
the reverse (config.yaml-only `required`) never got the extra from the
updater.

- `PlatformEntry.extra_names_fn` now takes the platform's PlatformConfig;
  Matrix's `_extra_names(config)` resolves the mode with the adapter's own
  `_resolve_e2ee_mode(config.extra)`.
- The updater's configured-features pass gates such entries per extra
  (`pm.extras.available`) under the loaded config instead of the env-only
  `check_fn`.
- `matrix_deps_present` (check_fn) is back to the plain SDK probe and
  `ensure_matrix_deps` (ensure_deps_fn) installs only `[matrix]`: neither
  sees a config, so `[matrix-e2ee]` installs at connect under the adapter's
  mode. `check_matrix_requirements` keeps main's env-based E2EE verdict for
  its setup/status callers.
2026-12-01 01:58:34 -08:00
Teknium
a0312a399c fix(matrix): install [matrix-e2ee] at connect for a config.yaml-only E2EE mode
The dependency gate (check_fn, ensure_deps_fn, updater extra_names_fn)
resolves MATRIX_E2EE_MODE from env only, while MatrixAdapter also reads
platforms.matrix.extra.e2ee_mode. With the encryption closure out of
[matrix], a YAML-only E2EE config got no python-olm. _connect_setup_e2ee
now installs [matrix-e2ee] off the event loop before judging the crypto
deps (required refuses, optional degrades, as before). zh-Hans docs now
distinguish optional fallback from required refusal.
2026-12-01 01:58:34 -08:00
Teknium
80b966cc4a fix(matrix): keep E2EE installs whole across the [matrix-e2ee] split
On top of the salvaged split (#130193):

- Name python-olm in [matrix-e2ee]. pm.extras._covered_extras reads
  `mautrix[encryption]` as plain `mautrix`, which [matrix] already covers,
  so the update's committed-generation carry dropped python-olm from every
  E2EE venv whose ledger records only [matrix].
- Leave [matrix-e2ee] out of opt-in-extras: Linux bundles shipped
  python-olm inside [matrix], so making it opt-in would strip E2EE from
  bundle installs on their next update.
- Keep the pip fallback in the E2EE install hint (main's
  test_matrix_encrypted_drop_warning contract) next to the
  `hermes pm install --extra matrix-e2ee` command.
- Install the E2EE extra through ensure_and_bind (logs and never raises),
  trim docstrings so adapter.py does not grow, add matrix-e2ee to the nix
  `full` package (it carried python-olm via [matrix]), and say in the docs
  that required mode refuses instead of falling back.
- Tests: the E2EE-off first start's uv.lock closure holds no python-olm;
  an update keeps [matrix-e2ee] for a generation holding python-olm.

Fixes #139398
2026-12-01 01:58:34 -08:00
Adrian Ma
d8f1717eb7 fix(matrix): gate the E2EE dependency closure behind its own extra
[matrix] pinned mautrix[encryption] on Linux unconditionally, so every
Matrix install built python-olm from sdist (no cp313/cp314 wheels) even
with MATRIX_E2EE_MODE=off, and hosts without a C++ toolchain lost Matrix.
Move the encryption closure to a new [matrix-e2ee] extra installed only
when E2EE is optional/required; the updater's configured-features pass
reads the extras a platform needs through PlatformEntry.extra_names_fn.

Net diff of #130193 (4 commits) applied onto current main; conflicts in
main_install_repair.py (declined extras), pm/extras.py, pyproject.toml and
tests/test_project_metadata.py resolved to keep main's newer code; uv.lock
regenerated with `hermes pm lock`.
2026-12-01 01:58:34 -08:00
Teknium
b53b9570a6 fix(memory): the missing-dependency notice says restart or why PM leaves a provider out
Independent review: two reproduced cases got the wrong remedy. A provider PM's
build leaves out because it does not support this Hermes (requires_hermes, or its
own hermes-agent requirement: pm.workspace.hermes_fit_error) was sent to
`hermes pm repair`, which can never install its dependencies; and a dependency
the selected generation already holds (installed after this process booted) was
sent to a rebuild when a restart loads it. The notice now names the version
misfit, or asks for a restart, and keeps the repair advice for the rest.
2026-11-30 23:12:26 -08:00
Teknium
6858f939bf fix(memory): a provider symlinked into the user plugins dir keeps the repair advice
find_provider_dir builds the candidate lexically (user dir / name), and
PM builds such a linked provider, so judge membership lexically instead
of requiring the resolved target to sit in the user dir (Greptile on
#162189).

Part of #134469
2026-11-30 23:12:26 -08:00
Teknium
f6bfd06f45 fix(memory): name hermes pm repair only for providers PM builds
PM adds only the active provider of the home's plugins dir to the
environment it records (pm.plugins_state.enabled_selection), so only
there does repair restore a missing declared dependency; project-local
and pip providers keep the generic notice (Greptile on #162189). Compute
the notice once in the failed-to-load warning.

Part of #134469
2026-11-30 23:12:26 -08:00
Teknium
ae52682219 fix(memory): a provider missing its declared Python deps says which and how to restore them
When the environment Hermes runs in lacks a user-installed memory
provider's declared dependencies (an update, repair or Store update rebuilt
it without them), startup said only that the provider "failed to load,
the log names the error", and `hermes memory status` said the plugin was
NOT installed and told the user to install it again.

Both now read the provider's declaration through the loader's own
predicate (missing_python_dependencies, new directory form
missing_dependencies_in) and name the missing requirements plus
`hermes pm repair`, then restart. Live: removing the dependency from a
real PM generation, then `hermes pm repair`, restores the provider.

Part of #134469
2026-11-30 23:12:26 -08:00
Teknium
f4024033fc fix(cron): hosted scheduled jobs fire without the API server channel (salvage #135023)
On hosted instances Chronos (NAS) calls the dashboard, which forwarded every
scheduled fire over loopback HTTP to the gateway's api_server platform. With
that channel switched off (or its key missing) every fire failed with 503 and
jobs only ran when triggered manually.

The dashboard now hands the fire to a new `cron-fire` verb on the gateway's
control socket, the owner-only local socket every running gateway binds
(startup aborts without it). The API server channel is no longer on the path
and is never turned on for cron.

- gateway/cron_fire.py: the verb. Same admission as the api_server route
  (verify, drain, ESTOP, cold-boot startup gate, durable claim, detached run
  with the live adapters), scoped to the job's profile home.
- CronScheduler.verify_fire (default: accept nothing); Chronos implements it
  with its existing verifier and cron.chronos settings, so core does not import
  the plugin to authenticate.
- control_dispatch: cron fires get their own worker pool, so a cold-boot burst
  waiting on startup never holds the workers identify/session-ticket use.
- The api_server POST /api/cron/fire route is unchanged for self-hosted
  callers that reach it directly; the boot warning that the api_server must be
  running for an external provider is removed.

Co-authored-by: Ben Barclay <ben@nousresearch.com>
2026-11-30 23:06:23 -08:00
Teknium
620ef5993f fix(discord): a cancelled disconnect still closes the client and frees the token lock
Independent review finding on #161790: the bounded asyncio.wait in
_cancel_bot_task propagates the caller's cancellation (reconnect watcher
cancel, gateway disconnect deadline), so disconnect() skipped
client.close() and the token-lock release, and a bot task that ignored
the first cancel stayed alive holding the token. The connect-failure
paths had the same gap for the lock. Run the cleanup in a finally and
let the cancellation propagate.
2026-11-30 15:17:22 -08:00
Teknium
d1282cb524 fix(gateway): a hung adapter dispose no longer stalls every platform reconnect (#142670)
The Discord bound alone (salvaged from #161333) waited 5s, the same as the
gateway's whole per-adapter disconnect budget, so on the bounded shutdown path
client.close() never ran and the orphaned client kept delivering. This bounds
the bot-task cancel at 2s through a reusable `cancel_task(timeout=)` helper,
then bounds `_dispose_unused_adapter` itself with the existing
detach-on-deadline primitive and disconnect timeout, so no adapter's
disconnect() can wedge the reconnect watcher that serves every platform.
2026-11-30 15:17:22 -08:00
salch-cred
87412242be fix(discord): bound _cancel_bot_task with asyncio.wait (#142670) 2026-11-30 15:17:22 -08:00
Teknium
9dceede1e8 fix(discord): choose the handoff thread type inline, drop the flat helper module
Review: a new flat adapter_<topic>.py sibling is not allowed by the
layout rules. The forum/text choice is two lines, so it moves inline into
create_handoff_thread; adapter.py stays at main's line count.
2026-11-30 15:05:29 -08:00
Teknium
72a126d9ab fix(discord): keep forum handoff homes off the thread-type kwarg
ForumChannel.create_thread has no `type` parameter, so passing
public_thread unconditionally made a forum handoff home die on a
TypeError before reaching Discord. Route the direct create through
adapter_thread_create.create_public_thread, which requests public_thread
only for non-forum parents (adapter._is_forum_parent), keeping adapter.py
at main's line count.

Adds a real-discord.py E2E: a TextChannel handoff sends type 11 on the
wire (main sends 12), a ForumChannel handoff still reaches the forum
endpoint.

Co-authored-by: negocki <4027589+negocki@users.noreply.github.com>
2026-11-30 15:05:29 -08:00
Majber
04c237f3a7 fix(discord): request public_thread in handoff direct thread creation
discord.py normalizes an omitted `type` on a message-less
TextChannel.create_thread() to private_thread, so handoff and continuable
cron threads were created private (bot-only, invisible to the channel).
Request ChannelType.public_thread explicitly on the direct path.

Salvage of #103085.
2026-11-30 15:05:29 -08:00
Teknium
0bb07e0353 fix(matrix): a brief homeserver blip no longer drops the catch-up replay
Review thread "Temporary failures lose offline messages": two 502s on the
catch-up sync exhausted the single retry and fell back to a tokenless sync, so
the offline messages were skipped and the advanced cursor saved.

Transient failures now share the 429 backoff (2/4/8 s on the same cursor,
inside the 30 s connect budget). A failure outlasting it still falls back to a
tokenless sync (logged at WARNING) so a since-sync the homeserver or proxy
cannot answer never keeps Matrix offline; only a persistent 429 fails the
connect with the cursor kept.
2026-11-30 15:04:25 -08:00
Teknium
8dd0db7599 fix(matrix): a rate-limited catch-up sync keeps the saved cursor
Independent review finding: a single 429 (M_LIMIT_EXCEEDED) on the catch-up
sync counted as a 4xx "cursor rejected", so the valid cursor was discarded,
the tokenless fallback sync skipped the offline messages and the advanced
cursor was saved over the good one.

A rate limit is now never a rejection: the catch-up sync backs off (2 s, 4 s,
8 s, within the 30 s connect budget) and retries the same cursor. If the
throttle outlasts that, CatchUpRateLimited fails the connect with
sync_token.json untouched, and the gateway's startup/reconnect retry resumes
from it.
2026-11-30 15:04:25 -08:00
Teknium
9110d50a1d fix(matrix): a send-only connect leaves the gateway's catch-up cursor alone
Independent review finding: a send-only adapter (cron delivery or `hermes send`
while the gateway is stopped) connected with catch-up armed, synced from the
gateway's saved cursor, dropped the offline message (no handler) and saved the
advanced cursor, so the gateway's next start resumed past it.

Catch-up is now armed per connect only when the adapter has a message handler
(the gateway wires it before connect()). A send-only connect does a plain
tokenless sync and never reads, advances or removes sync_token.json.
2026-11-30 15:04:25 -08:00
Teknium
e9cc913e78 fix(matrix): catch-up state lives in a MatrixCatchUp object, and a transient error no longer drops the replay
- MatrixCatchUpMixin -> MatrixCatchUp, an object the adapter owns
  (window, exempt event ids, startup-skip counts, E2EE backlog window)
  and calls explicitly. The clock-skew helpers go back on MatrixAdapter
  where main had them.
- Only a rejected cursor (4xx, malformed response) falls back to the
  tokenless sync. A transient since-sync failure retries once with the
  saved cursor, and a failed get_joined_rooms() keeps the successful
  catch-up response instead of discarding it (and overwriting the
  checkpoint with a tokenless batch).
2026-11-30 15:04:25 -08:00
Teknium
619122c089 fix(matrix): name the catch-up knob in the startup-skip warning and keep the E2EE backlog window open across catch-up events
- The startup-skip WARNING now tells the operator how to recover: with
  catch-up off it names platforms.matrix.extra.catch_up_window_seconds;
  with it on it says which drops were outside the window/checkpoint/cap.
- A replayed catch-up event is backlog, not the first live message: it
  no longer closes the E2EE "decrypted backlog" window, so older events
  decrypted after it are still counted and reported.
- catch_up.py -> adapter_catch_up.py (sibling naming), with the
  startup-skip summary helpers moved beside the grace logic; adapter.py
  stays smaller than on main.
- Test file reads/writes pass an explicit encoding (Windows footgun lint).
2026-11-30 15:04:25 -08:00
100yenadmin
3351de67ec fix(matrix): match the own join case-insensitively and warn when a disabled checkpoint stays 2026-11-30 15:04:25 -08:00
100yenadmin
4785e461e5 fix(matrix): prevent stale checkpoint replay 2026-11-30 15:04:25 -08:00
100yenadmin
88c1faad20 fix(matrix): guard catch-up replay and checkpoint failures 2026-11-30 15:04:25 -08:00
100yenadmin
fad4a25606 feat(matrix): opt-in catch-up of messages sent while the gateway was down 2026-11-30 15:04:25 -08:00
kshitijk4poor
c0f1d82150 refactor(matrix): drop a startup-skip flush that disconnect() already performs
connect() calls disconnect() whenever a previous client exists, and disconnect() flushes the open backlog window first, so the extra flush in connect() could never run. The first-message comment no longer claims the backlog has fully drained. Final-head gate (quality Lows).
2026-11-30 15:04:25 -08:00
kshitijk4poor
a5f14115ae fix(matrix): start each connect's startup-skip count from zero and pin the E2EE-only backlog window
Drops counted after the backlog window closed would otherwise be folded into the next connect's initial-sync summary with ages from the old startup. The test now opens the window through the real connect (E2EE on/off/quiet-room), so the bool(self._encryption) gate is covered: always-True and always-False both go red. Gate r3 Lows (2ab + 2c).
2026-11-30 15:04:25 -08:00
kshitijk4poor
daf34f6acf fix(matrix): accurate startup-skip wording and never lose pending E2EE backlog counts
The initial sync replays each room's recent timeline, so most skipped events after a plain restart were already handled by the previous process; the WARNING now says they are older than startup and that any sent while offline were not delivered. The late-decrypted backlog window opens only with E2EE, and is flushed by the first message past the gate, the first incremental sync (quiet room), disconnect, or the next connect - never silently discarded. One _NO_GRACE_SKIPS sentinel. Gate r2: quality Medium (wording) + Lows; 2ab/2c Low (quiet room / reconnect lose the pending count).
2026-11-30 15:04:25 -08:00
kshitijk4poor
db558557db fix(matrix): also report startup-grace drops of E2EE backlog decrypted after the initial sync
The initial-sync summary under-counted encrypted rooms (gate 2c UNVERIFIED,
now verified against mautrix 0.21.1, the pinned version). DecryptionDispatcher
registers its ROOM_ENCRYPTED handler with add_event_handler's default
wait_sync=False (client/dispatcher.py:35, client/syncer.py:167), so
_dispatch_manual_event runs it via background_task.create rather than
returning it among the tasks _dispatch_sync gathers (client/syncer.py:315-318).
The decrypted ROOM_MESSAGE is then re-dispatched from that background task
(client/encryption_manager.py:182-187). An offline E2EE DM backlog is
therefore grace-dropped after the summary was logged and never reported,
and the reporter's room was an E2EE DM.

After the initial summary, the first message that passes the startup gate
closes the backlog window and emits ONE more summary ("decrypted backlog")
if anything was dropped in between. Never per message. The counter is now
typed and its reset moves into _log_grace_skips.
2026-11-30 15:04:25 -08:00
kshitijk4poor
cfb0c1bf3b refactor(matrix): import _is_permanent_matrix_auth_error at module level
Gate finding (quality/2c Low): the sync loop late-imported it inside its
except branch on every sync error. adapter_sync.py imports nothing, so a
module-level import has no cycle risk.
2026-11-30 15:04:25 -08:00
kshitijk4poor
fbf0ad18aa revert(matrix): drop the reconnect outage-window delivery, keep the startup-skip warning
The reconnect half of the previous commit (shared MessageDeduplicator
seen_at/newest_seen_ts, Matrix's switch to it, and the _resume_ts grace
floor) targets a path the runner never takes for Matrix mid-run.

Reachability (gate 2c, re-verified on this branch): a platform enters
_failed_platforms mid-run only via _queue_retryable_fatal_platform, which
is reached from _notify_fatal_error. plugins/platforms/matrix/ never calls
_set_fatal_error, _notify_fatal_error or _acquire_platform_lock. A
transient sync error retries inside _sync_loop with the same
since=next_batch, and those outage-window events are newer than
_startup_ts, so main already delivers them. connect(is_reconnect=True)
only runs after a startup connect failure, where the failed adapter
normally saw no events. The test that pinned the outage window built a
state the runner cannot produce.

The cost was real: a shared-helper API change touching every
MessageDeduplicator user, and a Matrix dedup semantics change (origin-ts
eviction, O(n log n) sort per insert on a full cache). This restores
gateway/platforms/helpers.py and Matrix's deque/set dedup exactly as on
origin/main, removes _resume_ts, reverts the approval-reaction test helper
and deletes test_reconnect_delivers_outage_window_once. The per-connect
initial-sync WARNING stays.
2026-11-30 15:04:25 -08:00
kshitijk4poor
adc3afbad0 fix(matrix): log startup-grace drops and keep the outage window on reconnect
Messages sent while the gateway was down are dropped by the 5s startup grace filter with no log
line at all: the clock-skew heuristic (#27330) deliberately ignores the first 30s, so initial-sync
drops land in a silent window. Count grace drops per connect and emit one WARNING after the
initial sync ("skipped N message(s) sent while the gateway was offline ... not delivered").
Cold-boot behaviour is unchanged: the backlog is still not dispatched.

An in-process reconnect (connect(is_reconnect=True)) reset _startup_ts too, so a network blip lost
the outage window exactly like a cold boot. Mirror Telegram's watcher reconnect that preserves the
offline queue (#46621): the event-id dedup becomes a MessageDeduplicator keyed to origin_server_ts,
which the runner already carries into the rebuilt adapter (carry_inbound_dedup); on reconnect the
grace floor drops to the newest event already seen, and the same dedup stops re-dispatching it.

Persisting a watermark across process restarts (and a catch-up window knob) is left to a
maintainer decision.

Fixes #133265
Refs #27330, #46621
Reported-by: tilllt
2026-11-30 15:04:25 -08:00
kshitijk4poor
23794807b0 refactor(matrix): move _is_permanent_matrix_auth_error into adapter_sync to keep adapter.py under its size cap
Code-health ratchet: plugins/platforms/matrix/adapter.py is over the 2000-line target (3278 on main)
and may only shrink; the startup-grace fix that follows adds a few lines. Pure move of the sync-loop's
permanent-auth-error classifier and its errcode set (byte-identical) into a topical sibling; the sync
loop late-imports it. No other caller or test references either symbol.
2026-11-30 15:04:25 -08:00
Teknium
360c051387 fix(gateway): resolve WhatsApp LID aliases against the serving bridge's session dir only
Independent review finding: expand_whatsapp_aliases() unioned lid-mapping
files from the scoped profile dir and the launch home's dir, so two stores
that disagree about one LID made both numbers authorization aliases.

Resolve against ONE dir instead: the session dir the active profile's
bridge registered at connect (custom platforms.whatsapp.extra.session_path
included), else the launch home's bridge (serves a routed profile without
a bridge of its own, #135139), else the launch home's default dir.
2026-11-30 14:58:28 -08:00
Teknium
676987453d fix(discord): a rate-limited standalone POST reads at most 8 KiB of the 429 body
Independent review: post_paced read a 429 body with an unbounded resp.read(), so a
forum thread post that used to go through the 8 KiB error-body cap could buffer a
24 KiB (or larger) refusal whole. The capped reader moves into standalone_rest
next to post_paced; a 429 is read through it, and an oversized body waits the
Retry-After header instead of being parsed.
2026-11-30 14:33:33 -08:00
Teknium
6ebef2c275 fix(discord): standalone attachments stream from disk on every attempt
Greptile on #161891: the per-file upload read each attachment fully into
memory. multipart() now yields a context manager that reopens each path per
attempt, streams it and closes it after the request, so a 429 retry still
re-sends the whole body without buffering the file (the forum multipart
path, which buffered on main, streams too).
2026-11-30 14:33:33 -08:00
Teknium
556fac2d2e fix(discord): a standalone forum post or attachment survives a 429
Cron, `hermes send` and the send_message tool deliver to Discord through the
out-of-process REST sender. #152012 made its plain-text POST wait out a 429
and retry (standalone_rest.post_paced), but the forum thread post (JSON and
multipart), the per-file attachment upload and the missing-media caption
fallback still POSTed once: one 429 failed the whole forum post, or dropped
the attachment with only a warning.

Every standalone POST now goes through post_paced. Multipart bodies are
rebuilt per attempt (post_paced(form=...), standalone_rest.multipart),
because an aiohttp FormData is consumed by the request that sends it.

Probe (Discord stand-in, one 429 retry_after=0.3 on the first matching POST):
main: forum text/forum media -> success=False "(429)", attachment dropped
head: all four shapes delivered, attachment bytes intact.
2026-11-30 14:33:33 -08:00
alt-glitch
9c5fe135c6 refactor(tools): interrupt, hosted policy, thread context and the async bridge become tools/context.py
tools/context.py holds what a running tool call reads from its thread or
context. It takes tools/interrupt.py, tools/hosted_tool_policy.py,
tools/thread_context.py and agent/tool_progress_relay.py whole, and from
model_tools.py the sync-to-async bridge and the call ids. Function bodies are
unchanged. Three names other modules import lose their underscore: run_async,
CallIds and prompt_callback_accessors.

The file imports no other tool-core file, so the registry and every tool
module can import it at module top. tools/registry.py does, and no longer
imports the bridge from model_tools inside dispatch.

Old names. tools.interrupt and tools.thread_context keep importing through
MOVES keys, for pinned catalog plugins. tools/hosted_tool_policy.py and
tools/thread_context.py are generated files: a TUI, CLI or ACP process that
started on a release up to v0.23.5 and built no agent before the update imports
them when it builds a system prompt or compresses. agent.tool_progress_relay
gets nothing; in such a process the TUI row for MCP progress fails until it
restarts. model_tools keeps _run_async and _CallIds as second names for
run_async and CallIds until v0.27.0: the registry and the inline executors of a
release import them from model_tools inside functions, and without the first a
TUI or ACP process that outlives the update fails every tool with an async
handler.

Log lines follow their module to the logger tools.context. The interrupt trace
(HERMES_DEBUG_INTERRUPT) logs under tools.context.interrupt, so the level it
forces applies to the trace alone. The one line of the progress relay moves
from the agent log component to tools.
2026-11-30 23:20:42 +05:30
kshitijk4poor
04fb5c8c44 fix(gateway): metadata saves document what they write; the lock test checks the save landed
Follow-up to the review of #161759.

- `set_session_metadata` also carries Slack's thread watermark on every thread
  reply (#133891), not just a room's silence decision. Its docstring and the
  Slack adapter's `_set_thread_watermark` docstring said it was a full
  routing-index save with the fsynced sessions.json mirror; it is now one
  state.db row (full rewrite only as fallback).
- `_update_entry_metadata`'s docstring states its real contract: True once
  the mutation applied, and the mirror catches up on the next full save.
- The user guide's storage table says which per-turn fields reach the
  sessions.json mirror only on the next full save.
- The lock test now captures the worker's exception and reads each value back
  from a restarted store after the held write is released: `persist_turn_cwd`
  swallows save errors, so the old test passed even if the held save failed.
- The owner test's in-memory `_Store` docstring no longer claims a lock or a
  save it does not model.
2026-11-30 22:36:17 +05:30
alt-glitch
f4ec51785e refactor(utils): url_safety moves from tools/ to utils/
tools/ holds model tools. url_safety registers none: it is the SSRF guard
and the SSRF-safe HTTP clients that tools, the gateway, cron, the agent
and platform plugins call, so it moves to utils/url_safety.py. Function
bodies are unchanged; importers and patch targets follow the new path and
every import stays where it was. The four imports of hermes_cli it makes
carry an HX018 waiver naming why.

tools.url_safety is on the published plugin API, so the old name keeps
working: one MOVES key, one REQUIRED_NAMES row and the old-path file
written by scripts/move/generate_shims.py. Both names give one module
object. In-repo code, bundled plugins included, imports the new name
(tests refuse an old one); the plugin guide keeps the published name.

Three tests whose only subject is url_safety move to tests/utils/. The
logger is now utils.url_safety, which belongs to no hermes logs component.
2026-11-30 20:24:12 +05:30
alt-glitch
254349e445 refactor(xai): x_search and the xAI video tools register from the xAI plugins
The xai_video_edit and xai_video_extend tools move from tools/xai_video_tools.py into the xAI video
plugin (plugins/video_gen/xai/__init__.py). The x_search tool moves from tools/x_search_tool.py to
plugins/web/xai/x_search.py and is registered by the xAI web plugin. Both plugins register the tools
through ctx.register_tool, with the same names, toolsets, schemas, availability checks, required
environment and emoji. The tool list and every tool schema are unchanged.

A user can notice two differences. A call that leaves out prompt or query now gets the handler's own
error ("query is required for x_search") instead of core's generic missing-argument refusal, which
applies only to tools whose handler lives under tools/. Disabling the video_gen/xai or web/xai plugin
now also removes that plugin's tools.

x_search drops max_result_size_chars=100_000: the result budget is capped at that value already, so
the field changed nothing. The video tools drop self_checked_args, which only affects tools under
tools/. The boundary-lint baseline loses the core-to-plugin import that tools/xai_video_tools.py
made.
2026-11-30 19:41:40 +05:30