Commit Graph

50 Commits

Author SHA1 Message Date
Teknium
ad9229c843 feat(hooks): pre_llm_call can block a turn before any inference request
A pre_llm_call callback (Python plugin or shell hook) may now return
{"action": "block", "message": "..."} to veto the turn: no model call is made,
the message is the reply the user sees and the transcript keeps a normal
user -> assistant pair, and the result carries
turn_exit_reason=blocked_by_plugin_pre_llm_call. This is the supported seam for
DLP / privacy / policy plugins that previously had to patch core (#57364).

The vetoed prompt also stays on the host for that turn: no session titling call,
no external-memory prefetch or sync, no background memory review. Its user row
gets an api_content placeholder for the main-loop replay. That alone does not
keep the prompt out of later turns (compaction, session_search and memory
providers read the row's content); the next commit stores the placeholder as
the content.

First valid block wins; a Python block without a message is ignored (same as
pre_tool_call). Shell hooks accept both the Hermes {"action": "block"} and the
{"decision": "block", "reason": ...} shapes, mirroring pre_tool_call.
2026-10-31 22:59:20 -07:00
Teknium
6030e77121 fix(hold-stream): no side path delivers a held turn's original text
Independent review of the hold_stream feature found four paths that still
let the untransformed reply or commentary reach the user:

- History loads showed held commentary. The tool-call assistant row of a
  held turn is now typed display_kind="hidden" before its first flush
  (withhold_held_commentary), so TUI/Desktop display_projection, the
  dashboard and classic CLI resume skip it. display_kind never reaches the
  wire: the model's context and cached prefix are unchanged (test replays
  the resumed session and compares the request bytes). The TUI projection
  still labels the hidden row's tool cards from its calls. Codex held turns
  type their earlier agentMessages hidden the same way.
- A plugin reload mid-turn could empty the hook registry before the final
  transform. The held turn now snapshots its transform_llm_output callbacks
  together with the hold decision under the discovery lock
  (held_stream_transforms) and runs that snapshot at the final. If no
  callback rewrote and one raised or timed out, the user gets a fixed
  "reply withheld" notice instead of the original (fail closed).
- Classic CLI replay-gap recovery painted and spoke pre_transform_response.
  A held turn's result (generic and codex) no longer carries the original
  at all (public_pre_transform), so receipts, recovery and post-stream
  suffix painting only ever see the rewrite.
- Codex error-after-text returned the raw agentMessage. The codex reply is
  now transformed whenever it has text, also when the turn errored (and,
  when held, when interrupted).

Same class, also fixed: the end-of-stream scrubber flush recorded a held
tail as streamed text (an interrupted turn could return it as an
untransformed partial final), and quiet-mode CLI printed held commentary
via _vprint.
2026-10-25 06:18:48 -07:00
Teknium
fc6f517f09 fix(plugins): holds_stream() waits for an in-flight plugin reload
reload-plugins empties the ownership ledger before plugins re-register;
a turn starting in that window read holds_stream()=False and streamed
raw text the holding plugin must rewrite. Read the ledger under the
discovery lock so the turn sees the settled registration set.

Review: https://github.com/NousResearch/hermes-agent/pull/144266#discussion_r4369515508
2026-10-25 06:18:48 -07:00
Teknium
2eec2a7d24 feat(plugins): register_hook(..., hold_stream=True) for transform_llm_output
A plugin that rewrites the reply (redaction, policy filters) can declare that it
must see the reply before the user does. The declaration rides the hook's
registration handle, so it lives exactly as long as the registration and is
scoped to the plugin manager of the profile that loaded it; stream_held()
answers for the active profile. Plain transform registrations keep streaming
(opt-in), and the flag on any other hook is ignored with a warning. The memory-provider hook proxy and the
`plugins validate` probe stub accept the keyword so a declaring plugin loads
through every registration seam.

Shape and seams salvaged from #102481 (mutates= on register_hook, the memory
proxy and validate-stub forwarding).

Co-authored-by: Halldrix <12357213+Halldrix@users.noreply.github.com>
2026-10-25 06:18:48 -07:00
Teknium
a31975222e fix(plugins): post_compaction survives concurrent sessions and a failed projection
Key the bounded dispatcher's running-callback gate by session_id, so one
session's slow callback no longer skips another session's compaction. Fire the
gateway /compress hook in a finally after the receipt commits, so a failed
runtime projection cannot swallow it; exact retries (applied=False) still
never refire. Review findings from Greptile on #141017.
2026-10-18 02:31:09 -07:00
Teknium
ed9fb3cf56 fix(plugins): fire post_compaction on every committed compaction path
The salvaged hook fired from ContextCompressor.compress(), which is not where
a compaction commits: compress_context can still refuse or roll back the
candidate (snapshot stale, commit fence, split failure), the gateway's
/compress runs its own compressor and commits elsewhere, and Codex-native,
micro-compaction and proactive-prune rewrites never call compress() at all.
session_id was also the compressor's bound id, which is stale after rotation.

Fire it from the compaction-record seam (agent/compaction_events.py) that
already sees exactly one committed record per rewrite on every agent path,
and from the gateway session.mutate compress commit. Payload: session_id (the
session holding the compacted transcript), old_session_id, kind, reason,
before/after token estimates, messages_removed. Bounded by
plugins.hook_callback_timeout, since it runs inside the commit window.

Tests trimmed to one invariant (fires once per committed compaction, never
for an aborted one, raising plugin isolated); docs in hooks.md and the
plugin guide.
2026-10-18 02:31:09 -07:00
unsupportedpastels
4b6a8edd6a fix(plugins): fire pre_command in the gateway for every local command
After the cutover no local surface fired pre_command where the command runs.
slash.exec and command.dispatch (classic CLI forwards, Ink TUI, Desktop) never
fired it, and the classic CLI fired it from its own second copy of the plugin.

- The gateway fires pre_command for every recognized command a local session
  runs, under the session's profile: before the handler for commands it runs
  itself (slash.exec, command.dispatch; an accepted TUI read fires once inside
  the read path), and for commands the classic CLI runs in its own process
  through the new command.observe (plain data: the command as typed and its
  arguments). command.observe replies first, so the CLI never waits on a
  plugin. The hook arguments keep main's values: surface and platform "cli"
  on every local surface, session_key the session id.
- It fires only for commands that run. A busy rejection or a named refusal
  fires nothing; during a turn it fires when the busy dispatcher accepts the
  command, so a refused /goal, /loop or empty /queue or /steer fires nothing
  either. Every command that does run mid-turn fires, as main's CLI did,
  except messaging's escape hatches (/stop and the approval controls).
- Each delivery waits out its callback on its own thread, never the shared
  executor, with at most one delivery in flight per session: one session's
  deliveries fire in order and a slow callback never holds up another
  session's. The hook dispatcher's existing bounds apply
  (plugins.hook_callback_timeout and its abandoned-worker cap), and with
  plugins.isolation: host the hook runs in the plugin host. pre_command takes
  that bounded path everywhere, so off the gateway its callbacks also run on a
  worker thread.
- On a gateway session the classic CLI loads no plugin code. It reads skills,
  plugin commands and plugin toolsets from the gateway (commands.catalog,
  scoped to the session's own folder, and plugins.list) for /help, skill
  dispatch and completion, /tools and the status and banner fallbacks. -s and
  skills.auto_load are rendered in the gateway, and /reload-skills and
  /skills install rescan there and drop the CLI's cached catalog. These reads
  are cached per gateway life and never served once the connection has hung
  up. The "Unknown toolsets" warning comes from the gateway (a new
  unknown_toolsets field when the session opens). An older gateway without
  command.observe gets one named notice, and nothing fires locally.
- The canonical gateway connection serves plugins.list for its profile:
  loaded plugins with tool/hook/command counts, load error, toolsets and
  portable MCP server names (optional fields added to the contract; TS and
  OpenRPC regenerated). On a gateway session the CLI's /plugins reads it
  instead of this process's plugin manager. Off the gateway the in-process
  paths are unchanged.

Key-less inject_message (B2-11), which the classic CLI's own plugin copy
used to serve, is handled in the next commit.

Refs #134889 (PLG-7)
Refs #139523
2026-10-16 19:39:48 -04:00
Teknium
408cc0d12e Merge origin/main (#32: 36 commits to cf23a1a5cc) into feat/unified-gateway-runtime
17 conflicts, all from main's lint sweep (ruff UP007/UP017/UP022/UP028/UP031/UP037/UP041,
FURB188/FURB192); no other main commit touches a conflicted file. Resolution: the branch side
of each file plus main's exact autofix (ruff 0.15.10, main's ruff.strict.toml, --fix
--unsafe-fixes). ruff.strict.toml takes main's copy. The pool-retirement live fixture stays
deleted with the pooled backend this branch retires.
2026-10-09 10:24:04 -07:00
Maciej Lisiewski
aff64c3eeb ci: UP007, UP022, UP028, UP031, UP041 linter fixes 2026-10-09 17:31:52 +02:00
Teknium
65bec86e37 Merge origin/main (#27: 19 commits to 517b5e10fe) into feat/unified-gateway-runtime
45 conflicts, all from #135177 (lefthook + `ruff check --fix` over 2,366 files). No other main commit
touches a conflicted file. Resolution: the branch side of each file, then main's exact autofix
(ruff 0.15.10, `--config ./ruff.strict.toml --fix`) on it — rewrites only (typing generics, noqa
drops, import forms), no import removed. tests/cron/test_bot_chat_cli_home.py stays deleted
(1cc9cb9199 retired its lane).
2026-10-08 12:09:24 -07:00
Maciej Lisiewski
d76cce4f11 ci: apply all automatic linter fixes available 2026-10-08 17:22:54 +02:00
Teknium
a070a5be33 refactor(health): offset FILE_LINES growth by moving cohesive groups into topical siblings
main's ratchet caps every >2000-line facade at its main value; the PR grew seven.

- config.py: `hermes config show` rendering -> hermes_cli/config_show.py (reads config names via
  the module at call time so hermes_cli.config.<name> patch seams hold).
- backup.py: the cron prompt-field safety net -> hermes_cli/backup_cron_prompts.py; also drops a
  dead duplicate _PROTECTED_CONFIG_PATHS left by an earlier merge (the later definition won).
  restore_config_model_settings_* stay in backup: they are on the frozen old-updater surface.
- profiles.py: Honcho host migration on rename -> hermes_cli/profiles_honcho.py.
- plugins.py: resolve_plugin_command_result -> plugins_dispatch.py (re-exported from plugins,
  the public import path for cli/tui_gateway/plugins).
- main.py: --query-file reader -> hermes_cli/main_query_file.py.
- kanban_db.py: worker-context section renderers (_ctx_* + caps) -> hermes_cli/kanban_db_context.py;
  build_worker_context stays in kanban_db.
- config_defaults.py: drop the blank line the gateway block gained.

Patch-target retargets (moved symbols only): test_plugins.py (asyncio / await timeout now in
plugins_dispatch), test_managed_scope_surfacing.py (show_config import), test_backup.py
(restore_cron_prompt_fields_if_degraded import).

(cherry picked from commit 4079d422e0c2283c500c16885e959f5c170eb6cf)
2026-10-07 10:57:35 -07:00
Teknium
1e500ebce2 Merge origin/main (#16: 4,465 commits to 9dcab1e440) into feat/unified-gateway-runtime
99 conflicted files resolved in nine area lanes (Desktop composer, Desktop renderer/shared
client, Electron main, Ink, tui_gateway, gateway, state, CLI/config, cron/tools/CI). The
unified runtime's architecture wins where it deliberately replaced a mechanism (pool,
fallback lanes, claim poller, renderer queue); every orthogonal main change is kept, ported
into the <stem>_<topic> sibling that now owns relocated code.

Notable ports and repairs in this merge:
- tui_gateway/server.py relocated regions: atomic _attach_built_agent (#49852), slash ranking
  registry names, minted-key helpers methods_session.py calls, request_overrides, service tier.
- gateway/run_turn*.py: i18n accessors for the removed reply constants, first-contact
  internal/DM rule, rotated-compression persist, fast-mode tiers, prompt-pin rehydration.
- webhook: route_from_chat_id decodes main's opaque webhook:v2 chat ids (old ids still read).
- ws.py: main's per-connection dispatch queue with authority-first dispatch inside it.
- state: schema event for runtime revision renumbered to 31; worker mirrors updated for
  main's message uid/merge fields, on_contended lease arg, compression columns.
- config: branch's bot_chat_delivery_timeout removal renumbered v47 -> v50.
- Electron: primary-profile pin, redirect header scoping, remote fetchJsonForBackend, SSH
  teardown on profile delete, held-update dial gate restored (lost in earlier merges).
- Desktop: canonical clarify.request mapped to main's questions[] card; replay truncation vs
  snapshot_required; periodic secondary prune tick restored; DELETE already_absent restored.
- cron/tools: diagnostic category on cron failure notices restored; owner_holds_delivery
  ported onto the authority; admitted receipts can no longer be cancelled locally.
2026-10-06 14:24:24 -07:00
Teknium
be5481690d feat(gateway): reshape post_gateway_admission into a fail-open consume hook
Teknium ruled the post-admission consumer hook (#129958) must fail OPEN, so
reshape the salvaged implementation into one small seam:

- `{"action": "handled", "reply": str|None}` is the only decisive result;
  None, any other value, a raising callback or a timeout runs the ordinary
  agent turn. One buggy plugin can no longer blackhole every inbound
  message on a profile (the cherry-picked version failed closed on any
  exception or malformed return from ANY registered callback).
- Fire under the message's ROUTED profile scope. The receiving bot's
  handler binds the transport home so auth can read its .env; when that
  bot serves a chat for another profile, the ambient scope at the hook was
  the wrong profile and that profile's consumers never ran.
- Snapshot-only payload (session_key, platform, source dict, message_id,
  text): no live gateway runner / session store handles, so the plugin
  isolation host needs no HOST_DEGRADED_HOOKS entry.
- Bounded by plugins.hook_callback_timeout (fail-open) instead of the
  fail-closed policy-hook set; the required-but-discarded receipt, alias
  table, destination snapshot/restore machinery and hard-coded English
  failure notice are gone.
- Tests trimmed to three invariants through the real _handle_message and
  real plugin dispatch: consume path, raise path proceeds, routed profile
  scope bound.
2026-10-05 01:26:23 -07:00
JerryLiu369
b63305f379 feat(gateway): profile-scoped post-admission consuming gateway plugin extension (#129958)
Closes #129958
2026-10-05 01:26:23 -07:00
Teknium
f67d490f71 fix(plugins): trim request-middleware chaining to the minimal shape
Keep the contributors' fix (each llm_request / tool_request callback sees
the previous accepted rewrite; each gets its own copy of the payload and of
the original_* snapshot) in PluginManager.invoke_middleware, which stays the
single plugin-failure boundary, and drop the rest:

- the ~90-line iterative container walker in _safe_copy. It only runs when
  deepcopy fails (an opaque leaf in the request); main's shallow-copy
  fallback stays.
- the original_* freeze/copy in _run_execution_chain. Execution middleware
  already composes via next_call; that was defensive isolation, not chaining.
- the second copy of an accepted return inside invoke_middleware
  (_apply_request_chain already copies it).
- tests/hermes_cli/test_middleware_isolation.py and the test_plugins.py
  additions; tests/hermes_cli/test_plugins_middleware_chain.py holds two
  invariant tests (composition, in-place-mutation isolation), each over
  both request kinds. test_plugins.py is over its size cap, so it gains
  nothing.
2026-10-05 00:22:31 -07:00
itsflownium
202bb0431b fix(plugins): isolate snapshots and nested middleware requests 2026-10-05 00:22:31 -07:00
itsflownium
6540d9a82b fix(plugins): isolate and compose accepted request middleware rewrites 2026-10-05 00:22:31 -07:00
nekwo
ecf6114229 fix(plugins): chain request middleware so each callback sees the previous rewrite
_apply_request_chain fanned every llm_request / tool_request callback out
over the ORIGINAL payload and kept only the last result, so a second
plugin's rewrite silently dropped the first's. A new
PluginManager.invoke_middleware_chain threads each dict result under the
payload key into the next callback; invoke_middleware is unchanged, and a
manager without the new entry point falls back to the flat fan-out.

Test: test_request_middleware_chains_each_callback_onto_the_previous_result
— red before (payload missing {'a': True}), green after. Touched files:
178 run, 3 failed — the same 3 fail on unmodified upstream/main 5bb2be179d.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 00:22:31 -07:00
teknium1
eec5bd6673 Merge remote-tracking branch 'origin/main' into fix/106742-thread-resolution
4,048 upstream commits (Sep 16-23) composed onto the unified gateway runtime by six
per-domain conflict lanes (gateway, desktop/shared, cli/state, cron, bots/tui_gateway, ink).
Retired lanes stay retired (Desktop secondary pool + exit supervisor, deferred Bot Chat
pending queue, subprocess retry adoption); main's gateway.standalone, host-role claim,
clarify capability gate, config-read caches and idle gates ride on top.
2026-09-23 03:25:31 -07:00
teknium1
0e5809566f feat(plugins): fire pre/post_auxiliary_call events on every auxiliary LLM call (#79733)
Auxiliary LLM calls (titling, compression, MoA advisors/aggregator, vision,
approval, ...) never reached any plugin hook: hook-based observability and
cost plugins were structurally blind to them. Teknium's ruling on #79733:
NEW events rather than reusing the turn-scoped pre/post_api_request pair,
so existing subscribers keep their per-turn semantics.

- agent/auxiliary_hooks.py (new sibling): builds the pre_api_request /
  post_api_request payload shape plus `aux_task`, `api_request_id`
  (`aux-...`, shared by every attempt of one logical call), `retry_count`,
  `streaming`, parent-turn `session_id`/`task_id`/`turn_id` when a main
  turn is in flight; fail-open (a raising/hung subscriber is logged and
  the aux task proceeds); post carries `error`/`error_type` on failure.
- agent/auxiliary_client.py: the three relay funnels every physical
  attempt shares (_relay_sync_completion / _relay_async_completion /
  _relay_sync_stream) run under the hook pair — retries and fallbacks
  included. Main-loop *_api_request events do not fire for aux calls.
- Catalogue: VALID_HOOKS, bounded-timeout hook set, `hermes hooks test`
  sample payloads, hooks.md / plugins index / observer-hooks / plugins.md
  tables, agent + plugins AGENTS.md.
- tests/agent/test_auxiliary_hooks.py: 2 invariants (pair fires with
  aux_task and no api_request events; raising subscriber never breaks
  the call). First is red on origin/main.

Supersedes #32416 (@zrmnelson), #68060 (@JonZal), #77518 (@hsy5571615),
#79826 (@webtecnica) — their relay-boundary placement, usage
normalisation and fail-open policy shaped this implementation.

Co-authored-by: zrmnelson <zacharynelson1@gmail.com>
Co-authored-by: Jonas Zalys <jonas@tryholo.ai>
Co-authored-by: saitsuki <nukuom976228@gmail.com>
Co-authored-by: webtecnica <webtecnica@gmail.com>
2026-09-22 01:19:12 -07:00
teknium1
75e9567ca7 fix(plugins): ainvoke_hook shares the sync path's failure contract
Follow-up trim of the #110265 salvage. `ainvoke_hook` logged raising callbacks
with a bare warning; route them through `_report_hook_failure` (warn-once per
distinct failure, #111922) and, for `_HOOK_TIMEOUT_FAIL_CLOSED_HOOKS`, append
the same named block directive the sync path emits (#109624), so the async twin
cannot drift into a fail-open policy path. Tests trimmed to the salvage bar: the
in-loop await is proven once through the real `_handle_message` path
(`test_async_hook_callback_is_awaited_on_the_gateway_loop`); the manager-level
duplicate is dropped and the narrowing test also pins failure isolation. Docs:
`pre_gateway_dispatch` callbacks may be `async def` and stay unbounded.

Credit order for the three PRs fixing this gap: #102485 (dmspark, earliest,
pre-decomposition `gateway/run.py`), #110253 (KoNit-K, bounded the hook —
rejected by design: neither fail mode is acceptable for a policy gate), #110265
(twidtwid, reporter; cherry-picked because it matches the ainvoke_hook shape,
keeps the hook unbounded, and adapts the existing sync test seams honestly).

Part of #110241
Supersedes #102485
Supersedes #110253
Co-authored-by: David Marcus <dmspark@users.noreply.github.com>
Co-authored-by: KoNit-K <konit.block@protonmail.com>
2026-09-21 23:47:51 -07:00
Todd Dailey
727e7342cf fix(gateway): await async pre_gateway_dispatch callbacks on the event loop
`GatewayInboundMixin._hm_pre_gateway_dispatch_hook` was a plain `def` calling
the sync `hermes_cli.lifecycle.invoke_hook` from the async `_hm_admit_event`,
so an `async def pre_gateway_dispatch` callback was resolved through
`resolve_plugin_command_result` on a helper thread with its own loop: the
gateway loop blocked for the callback's whole duration and any loop-bound await
(an `asyncio.Event` set by a loop task, a loop-bound aiohttp session,
`asyncio.to_thread`) could never complete, failing at 30s.

Add `PluginManager.ainvoke_hook` (+ `hermes_cli.plugins.ainvoke_hook` /
`hermes_cli.lifecycle.ainvoke_hook`): same payload narrowing (shared
`_hook_callback_kwargs`), observer + isolation semantics and result contract as
`invoke_hook`, but awaitable results are awaited on the caller's loop.
`pre_gateway_dispatch` stays intentionally unbounded. The inbound hook becomes
`async def` and `_hm_admit_event` awaits it; the sync `invoke_hook` is untouched
for every other caller. Existing tests that stubbed the hook synchronously are
adapted to the async seam.

Fixes #110241
Salvages #110265

(cherry picked from commit 22bb10d305c7992f43bbfdf1481ad0ef0015b2b7)
2026-09-21 23:47:51 -07:00
teknium1
3755520916 fix(plugins): a hung pre_tool_call guard no longer blocks every tool call until restart
`_run_hook_callback_bounded` treated any live abandoned worker for a callback
(`bool(self._hook_abandoned.get(suppression_key))`) as "still running", so one
never-returning `pre_tool_call` callback made every later tool call fail closed
with the timeout message until the process restarted. The timeout path
self-heals through the 60s suppression window; the abandoned path never did.

Policy now: while the suppression window is open the callback is skipped as
before. After it expires a fresh call id may start a new worker even though the
abandoned one is still alive — capped at `_HOOK_MAX_ABANDONED_WORKERS` (3) live
abandoned workers per callback so a hung plugin cannot leak a thread per call
(the #98382 constraint). At the cap the callback keeps being skipped (fail-closed
for pre_tool_call) with a WARNING naming the callback and its module, until one
of its workers finishes and frees a slot.

Test changes: `test_hung_worker_blocks_new_call_identity_after_suppression`
encoded the removed behaviour (exactly one worker, forever); it becomes
`test_hung_worker_caps_new_call_identities_after_suppression`, which pins the
same invariant it was protecting — bounded leak, never one per call — at the new
bound and checks the warning. `test_hung_worker_does_not_fail_closed_forever`
is the #105223 regression (red on base: call-c returned the block directive).

Redone slim against the per-call-id gate that landed in #111177; #105241
targeted the pre-#111177 shape and needed plugins_ledger/__init__ changes for a
one-retry-then-quarantine policy. Its analysis and shape informed this fix.

Fixes #105223
Supersedes #105241
Co-authored-by: fangliquanflq <fangliquan@qq.com>
2026-09-21 23:47:51 -07:00
teknium1
32518f024f fix(plugins): name the callback and error in the raise-fail-closed block
Follow-up trim of the #109632 salvage: the block directive a raising
`pre_tool_call` guard produces reused the timeout wording, so an operator could
not tell a crashing guard from a slow one from the tool result. Build it from
the callback name and `TypeError: ...` (error text truncated like
`_report_hook_failure`). The two salvaged tests collapse into one parametrized
invariant (caller-thread and bounded-worker path) that also pins the message
shape and that a sibling callback's result still flows.

Part of #109624
Salvages #109632
2026-09-21 23:47:51 -07:00
KoNit-K
89de608317 fix(plugins): fail closed on policy hook exceptions
A `pre_tool_call` guard that raised failed OPEN (only `_report_hook_failure`,
results stayed empty, the tool ran) while one that timed out failed CLOSED with
a block directive. For a veto hook a crashing guard is the control quietly
disappearing; make both failure modes of `_HOOK_TIMEOUT_FAIL_CLOSED_HOOKS`
consistent: an exception appends a block directive in addition to the warning.

Fixes #109624
Salvages #109632

(cherry picked from commit 6ccf5d8a4082fc6b9af80270aae9f13b0320cfb8)
2026-09-21 23:47:51 -07:00
teknium1
e49436b78d fix(profiles): plugin hooks from a launch-profile turn run under a bound profile scope
Under a multiplexed gateway / serve backend the launch profile's own turns bound
secrets and terminal policy but NO HERMES_HOME override (launch_profile_runtime_scope,
_profile_runtime_scope_tokens(None)). Once multiplexing is active an unset override
is the fail-closed "unbound context" signal (serves_routed_profile, per-home slots,
third-party runtime bindings such as OMH's pre_tool_call gate), so every plugin hook
a launch-profile turn fired looked unscoped and a fail-closed plugin vetoed every
tool call ("OMH runtime binding unavailable", #118538). Routed turns already bind
theirs via gateway/run.py::_profile_runtime_scope; the launch profile is a tenant
like any other, so its scope now binds the launch home too.

Sibling gap in the two hook kinds delivered off-turn by long-lived worker threads:
agent.plugin_stream_hooks (on_stream_*/on_interim_message) and the plugin event bus
(plugins_dispatch._dispatch_event) ran callbacks in the worker's empty context, so
even a routed turn's observers saw no scope. Both now capture the emitter's
contextvars at enqueue and run each delivery under a copy.

Single-profile hosts are unchanged (no override until activation).

Closes #118538
2026-09-21 18:43:43 -07:00
teknium1
656c1c9bda fix(plugins): isolate SystemExit in event, middleware and prompt-section callbacks too
The hook loop now treats SystemExit like any other callback failure; the
three sibling dispatch loops in this module (event subscribers,
invoke_middleware, system prompt section content) had the same
`except Exception` gap and let a plugin dependency's sys.exit() abandon
the loop and kill the turn. KeyboardInterrupt still propagates on all
of them.
2026-09-20 15:21:14 -07:00
Jony
d1221d43b7 fix(plugins): isolate SystemExit from hook callbacks
(cherry picked from commit 99facb98dc9e9c88af6c4fcc1049c6018871e520)
2026-09-20 15:21:14 -07:00
teknium1
3f80dc9a5a fix(plugins): stream observer hooks and event subscribers fail-report once, not per event
Two per-call WARNING surfaces were still outside the warn-once reporter:

- agent/plugin_stream_hooks.py::_worker — the on_stream_start/on_stream_delta/
  on_stream_end consumer, which fires once per streaming delta (far more often than
  per tool call). A mis-declared callback (signature naming tool_data) logged
  "Hook ... raised" at WARNING on every delta: 20 deltas -> 20 WARNING lines.
- hermes_cli/plugins_dispatch.py::_deliver_event — plugin event subscribers that
  raise identically were warned on every emit.

Both now go through PluginManager._report_hook_failure (keyed by module/qualname,
cleared on unload): the first failure warns and names the fields the hook/event
provides, identical repeats are DEBUG. Skip-and-continue semantics are unchanged.

Part of #111922
2026-09-17 09:03:29 -07:00
teknium1
cbf2d2e598 Merge remote-tracking branch 'origin/main' into fix/106742-thread-resolution
# Conflicts:
#	apps/desktop/electron/main.ts
#	hermes_cli/web_server.py
#	tests/tools/test_bot_retry_policy.py
#	tools/bot_mode_dm.py
#	tools/bot_relay.py
#	tui_gateway/methods_bot_relay.py
#	tui_gateway/server.py
2026-09-16 17:34:01 -07:00
teknium1
01d73210c2 fix(plugins): dedupe middleware failures too, and let unload forget reported hook failures
Review follow-up on the warn-once hook reporter. Middleware (agent_tool_execution
etc.) runs once per tool call exactly like a hook, so a mis-declared middleware
callback flooded WARNING identically; route its except through the same
_report_hook_failure helper with a "Middleware" surface label.

The reported-failure set was keyed on (hook, id(cb), repr(exc)) and never
cleared: a hook whose message embeds tool args grew it by one entry per call,
and id() recycling across plugin reloads could swallow a reloaded callback's
first failure. Key on (hook, module, qualname, exc type, str(exc)[:200]) and
clear the set in _reset_after_unload_all next to _hook_timeout_suppressed_until.

Part of #111922
2026-09-16 17:08:25 -07:00
teknium1
8beeb661c9 fix(plugins): report an identically failing hook callback once, not on every call
A plugin callback whose signature names a parameter the hook never sends
(on_pre_tool(tool_data) where core provides tool_name/args) raises the same
TypeError on every tool call; core logged a WARNING each time — ~1700 lines an
hour in the report, burying the freeze signature it was trying to find
(finding (c) of #111922). The mis-declared signature is the plugin's bug; the
per-call repeat is ours.

invoke_hook now reports one WARNING per distinct (hook, callback, error) and
names the fields the hook actually provides so the author can fix the
signature; identical repeats are logged at DEBUG. A callback failing in a new
way still warns.

Part of #111922
2026-09-16 17:08:25 -07:00
teknium1
43c477571e Merge origin/main (61154b6f68) into feat/unified-gateway-runtime
1,446 upstream commits; 84 conflicted files resolved per family, porting
every post-branch main fix onto the cutover architecture rather than
dropping it or resurrecting replaced pre-cutover code:

- gateway/cron/kanban/a2a: #111988 hygiene bound, silence-marker rejection,
  UX copy, clarify-card retirement on explicit no-answer, Slack task-card
  publication_suppressed, webhook per-route coalescing (wrapping the durable
  admit_producer), kanban dead-worker last output + fingerprint boot witness,
  migrate-profile-identity control verb, SupervisedTickerThread, api-server
  terminal_run_status; config migration 45 kept from main, ours renumbered 46.
- hermes_cli/hermes_state/tools/tui_gateway: read_only SessionDB alongside
  explicit db_path, sessions_cmd observational flag, #111958 served-profile
  skips service install, #111999 usage source upsert repair, archived Bot Chat
  title release, find_canonical_owner, #111151 serves_routed_profile MCP scope,
  session_search after/before/exclude, server.py hunks into session_registry/
  agent_factory siblings, #111775 runtime_check resolve hook, Bot Chat
  silence rule on delivery reply.
- Desktop/apps/shared: pool modules stay deleted; SSH teardown fencing,
  default-profile + peer-window routing, per-session remote headers,
  server->client requests, generated gateway contract with our owner stamps
  and session.replay_gap retained.
- Ink: canonical WebSocket client kept; storedSid reconnect recovery, server
  request store, generated contract types, plain-language copy ported.
2026-09-16 13:20:14 -07:00
kshitijk4poor
73f808e47f fix(plugins): only mark a timed-out hook worker abandoned while it still holds its token
The timeout branch of _run_hook_callback_bounded unconditionally added
gate_key to _hook_abandoned. A worker that finishes between done.wait()
returning False and the caller taking the lock has already popped its
token via _release_token, so nothing would ever clear that entry: the
callback stayed blocked for every later call id until reload with no
thread behind it. Guard the insert on the worker still being registered.

The new test makes the race deterministic by swapping the module's
threading.Event for one whose wait() lets the worker finish and then
reports a timeout, and asserts a fresh call id still runs.

Also pass tool_call_id inline from terminal_tool_result instead of the
conditional dict plumbing: an empty id is already treated as "no
identity" by _hook_call_identity and unknown fields are withheld from
narrow-signature callbacks (same shape as _fire_approval_hook). Update
the stale "(hook_name, id(cb))" comment above _hook_running_callbacks.
2026-09-15 10:48:49 +05:30
kshitijk4poor
cdd58810a4 fix(plugins): keep one worker per callback while a timed-out worker is still running
Gating hook callbacks by call identity lets two concurrent calls of the
same tool both run their hooks, but it also let a fresh tool_call_id pass
the gate once the 60 s suppression window lapsed even though the previous
worker for that callback never returned. A hung plugin then leaked one
daemon thread per minute for the life of the process; on the old
coarse-keyed gate it leaked exactly one.

Track abandoned-but-running workers per callback: the timeout branch
records the gate key, the worker's own release discards it, and the gate
treats any non-empty abandoned set as "still running" for that callback.
Healthy callbacks keep distinct-id concurrency; hung ones are back to
at most one outstanding worker.
2026-09-15 10:48:49 +05:30
deadczarvc
4121aa295a fix(plugins): gate hook callbacks by call identity, not by tool name alone
Concurrent invocations of the same tool in one session collapsed into a single
busy key (hook_name, id(cb)): the second invocation was reported as 'still
running' and dropped. For pre_tool_call a drop is a fail-closed block, so the
gate silenced itself on an ordinary, healthy callback.

Measured on a busy profile: 3574 skip lines and 0 timeout lines in one hour —
every skip was the 'while still running' branch, i.e. pure key collision, not
slowness.

The gate now keys on the call identity that is already in the payload
(tool_call_id, else turn_id, else none — the last case behaves exactly as
before). Suppression stays keyed coarsely on (hook_name, id(cb)): a hung
callback is a fact about the callback, so its back-off must not be diluted
per call.

Refs #98382. Independent of #107894 (that one releases the slot on timeout;
this one stops healthy concurrency from colliding).

(cherry picked from commit 53b3dacd008418fcdf5fa6dfcadde575a35a776e)
2026-09-15 10:48:49 +05:30
teknium1
e3c497f04f Merge origin/main into feat/unified-gateway-runtime (Sep 12)
# Conflicts:
#	agent/subdirectory_hints.py
#	gateway/run.py
#	gateway/run_turn.py
#	hermes_cli/config_migrations.py
#	tests/hermes_cli/test_config.py
2026-09-12 11:31:43 -07:00
teknium1
24444e52eb fix(plugins): await async hook callbacks instead of collecting bare coroutines
Slash-command handlers gained loop-safe awaiting in ca9a61ae38, but
`PluginManager.invoke_hook` still called `async def` hook callbacks directly:
the coroutine object was appended to the results (so `pre_llm_call` context
injection silently did nothing) and Python warned "coroutine was never
awaited". `_invoke_hook_callback` now routes every return through
`resolve_plugin_command_result`, which covers both the direct and the
timeout-bounded paths and is safe under the gateway's running loop.

Fixes #12449 (remaining hook half). Salvage of #63240 by @Bartok9, applied
one layer down so the bounded-worker path is covered too.

Co-authored-by: Bartok9 <Bartok9@users.noreply.github.com>
2026-09-12 08:26:48 -07:00
Teknium
33921e6f97 feat: bypass plugin providers and hook execution in safe workers 2026-09-08 18:51:41 -07:00
kshitij
a188c84871 refactor(plugins): share the hook-token release between runner and start-failure paths
The identity-guarded token pop appeared twice (the runner's finally and the
new worker-start except); a future edit to one copy would silently reintroduce
the sticky-token class. Hoist into a local closure called from both sites, and
extend the _run_hook_callback_bounded docstring with the new skip reason.
Behavior-preserving follow-up on #104651.
2026-09-07 13:11:36 +05:30
Bruce Xu
5f561efe67 fix(plugins): recover when hook worker cannot start 2026-09-07 13:11:36 +05:30
Teknium
e83816a4d1 review-fix(comments): restore lost #NNNN rationale comments across non-test source (mechanical sweep, condensed, code unchanged)
For each issue anchor present in BASE 63279301bc non-test .py and absent on HEAD, the BASE comment/docstring block was re-attached at the HEAD location of the code it explained (matched by the distinctive code line / enclosing def). Sentences already covered by an existing HEAD comment were deduped; the issue number always survives. Insert-only: no code lines changed.
2026-09-03 09:44:26 -07:00
Teknium
d127749b23 refactor(hermes_cli): inline single-use plumbing helpers (portable manifest read, pulled-revision record, entrypoint listing, timeout block) 2026-09-02 22:24:36 -07:00
Teknium
761686347c refactor(hermes_cli): hug closing brackets in plugin CLI modules (AST-identical) 2026-09-02 21:10:03 -07:00
Teknium
b10a148053 refactor(hermes_cli): AST-neutral statement packing across plugin CLI modules 2026-09-02 20:37:05 -07:00
Teknium
53d082c678 refactor(hermes_cli): compact plugins_dispatch constants and dispatch bodies 2026-09-02 20:24:45 -07:00
Teknium
7f02cb7e1e refactor(cli/plugins): trim re-exports to referenced names; drop isort blanks after in-function imports 2026-09-02 15:57:40 -07:00
Teknium
d7c64815a7 refactor(cli/plugins): repack multi-line statements to <=100 cols (AST-identical) across plugins*.py 2026-09-02 15:53:53 -07:00
Teknium
f0cfbb33e1 refactor(cli/plugins): move hook/event-bus/prompt-section dispatch into PluginDispatchMixin (plugins_dispatch.py) 2026-09-02 15:41:50 -07:00