The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(hooks): keep in-memory consent across re-syncs; never disarm on malformed input
kshitijk4poor29f98a6e1a62
diff --git a/agent/shell_hooks.py b/agent/shell_hooks.pyindex 770b665edfe..e8c70a6cecf 100644--- a/agent/shell_hooks.py+++ b/agent/shell_hooks.py@@ -55,6 +55,14 @@ _registered_lock = threading.Lock()# Non-POSIX fallback for allowlist read-modify-write. Must be separate from _registered_lock, which# register_from_config already holds when it triggers _record_approval (Lock is non-reentrant)._allowlist_write_lock = threading.Lock()+# sync_from_config: read + apply as one step, so an older snapshot never lands after a newer one.+_sync_lock = threading.Lock()+# Consent that lives only in this process (guarded by _sync_lock): (home, event, command) a launch's+# --accept-hooks approved but the allowlist does not hold yet, this process's own --accept-hooks, and+# the skipped hooks already logged.+_launch_consent: set[tuple[str, str, str]] = set()+_process_accept = False+_skip_logged: set[tuple[str, str, str]] = set()def _home_key() -> str:@@ -141,12 +149,14 @@ class ShellHookSpec(_ToolMatcherMixin):def register_from_config(cfg: Optional[dict[str, Any]], *, accept_hooks: bool = False) -> list[ShellHookSpec]:"""Register every configured shell hook (idempotent); returns the newly wired specs. Skippedentries (unknown, malformed, not allowlisted, already registered) are logged only."""- specs = _hook_specs(cfg)+ specs, _complete = _hook_specs(cfg)if not specs:return []- accept, allowed = _resolve_effective_accept(cfg, accept_hooks), _allowlisted_pairs()from hermes_cli.plugins import get_plugin_manager # lazy: avoids import cyclemanager, home_key = get_plugin_manager(), _home_key()+ with _registered_lock: # an already-wired hook is never re-asked for (main checked this first)+ specs = [spec for spec in specs if _key(home_key, spec) not in _registered]+ accept, allowed = _resolve_effective_accept(cfg, accept_hooks), _allowlisted_pairs()# TTY prompt outside the lock; _wire takes the lock and re-checks.consented = []for spec in specs:@@ -160,36 +170,50 @@ def register_from_config(cfg: Optional[dict[str, Any]], *, accept_hooks: bool =return _wire(manager, home_key, consented)-def sync_from_config(cfg: dict[str, Any]) -> None:- """Bring this home's registered shell hooks in step with ``cfg`` and its consent, for a- long-lived process (the gateway) that must behave as a new process would: hooks configured and- consented since start register, hooks removed from ``cfg`` or revoked are unregistered. Consent- is the allowlist, or an opt-in in force (``hooks_auto_accept`` / ``HERMES_ACCEPT_HOOKS``), which- approves every configured hook as on main, even one whose allowlist write failed. Never prompts- or writes. An empty ``cfg`` (a loader that failed open) or an unreadable allowlist must never- disarm a ``fail_closed`` guard, so either adds but never removes."""- specs = _hook_specs(cfg)- if not specs and not cfg:- return- allowlist, readable = _read_allowlist()- allowed = _approved_pairs(allowlist["approvals"])- accept = _resolve_effective_accept(cfg, False)- wanted = [spec for spec in specs or [] if accept or (spec.event, spec.command) in allowed]+def sync_from_config(load_cfg: Callable[[], dict[str, Any]]) -> None:+ """Bring this home's registered shell hooks in step with its config (``load_cfg()``) and+ consent, for a long-lived process (the gateway) that must behave as a new process would: hooks+ configured and consented since start register, hooks removed from config or revoked are+ unregistered. Consent is the allowlist, an opt-in in force (``hooks_auto_accept`` /+ ``HERMES_ACCEPT_HOOKS`` / this process's own ``--accept-hooks``), or a launch's ``--accept-hooks``+ whose allowlist write failed (``accept_for_launch``). Never prompts or writes. An empty config+ (a loader that failed open), a malformed ``hooks:`` entry or an unreadable allowlist must never+ disarm a ``fail_closed`` guard, so each adds but never removes. Config and allowlist are read+ under the same lock as the apply, so the last sync to run always applies the newest state."""from hermes_cli.plugins import get_plugin_manager # lazy: avoids import cycle- manager, home_key = get_plugin_manager(), _home_key()- # One lock hold for add + remove: a concurrent sync on an older snapshot can never drop what a- # newer one just added.- with _registered_lock:- _wire(manager, home_key, wanted)- if specs is None or not readable:+ with _sync_lock:+ cfg = load_cfg()+ specs, complete = _hook_specs(cfg)+ if specs is None or not cfg:return- keep = {(home_key, spec.event, spec.matcher, spec.command) for spec in wanted}- stale = {k for k in _registered if k[0] == home_key and k not in keep}- _registered.difference_update(stale)- for event in {k[1] for k in stale}:- # Replaced, never edited in place: a concurrent invoke_hook keeps iterating the old list.- manager._hooks[event] = [cb for cb in manager._hooks.get(event, [])- if getattr(cb, "shell_hook_key", None) not in stale]+ allowlist, readable = _read_allowlist()+ allowed = _approved_pairs(allowlist["approvals"])+ home_key = _home_key()+ # A launch approval the allowlist now holds is the allowlist's to keep (or revoke).+ _launch_consent.difference_update({(home_key, *pair) for pair in allowed})+ allowed |= {(event, command) for home, event, command in _launch_consent if home == home_key}+ accept = _resolve_effective_accept(cfg, False)+ wanted = []+ for spec in specs:+ if accept or (spec.event, spec.command) in allowed:+ wanted.append(spec)+ elif (home_key, spec.event, spec.command) not in _skip_logged: # once per process, not per open+ _skip_logged.add((home_key, spec.event, spec.command))+ logger.warning("shell hook for %s (%s) not allowlisted — skipped. Approve it at a CLI prompt, "+ "or use --accept-hooks / HERMES_ACCEPT_HOOKS=1 / hooks_auto_accept: true.",+ spec.event, spec.command)+ manager = get_plugin_manager()+ with _registered_lock:+ _wire(manager, home_key, wanted)+ if not (readable and complete):+ return+ keep = {_key(home_key, spec) for spec in wanted}+ stale = {k for k in _registered if k[0] == home_key and k not in keep}+ _registered.difference_update(stale)+ for event in {k[1] for k in stale}:+ # Replaced, never edited in place: a concurrent invoke_hook keeps iterating the old list.+ manager._hooks[event] = [cb for cb in manager._hooks.get(event, [])+ if getattr(cb, "shell_hook_key", None) not in stale]for _home, event, _matcher, command in stale:logger.info("shell hook unregistered (removed from config or allowlist): %s -> %s", event, command)@@ -198,7 +222,7 @@ def record_consent_from_config(cfg: Optional[dict[str, Any]], *, accept_hooks: b"""First-use consent without registering anything, for a client whose turns run in a gateway thathas no TTY: the prompt (or an opt-in) for each configured hook not yet allowlisted. The gatewayregisters from the same allowlist when the client opens its session."""- specs = _hook_specs(cfg)+ specs, _complete = _hook_specs(cfg)if not specs:returnaccept, allowed = _resolve_effective_accept(cfg, accept_hooks), _allowlisted_pairs()@@ -206,24 +230,50 @@ def record_consent_from_config(cfg: Optional[dict[str, Any]], *, accept_hooks: b_consented(spec, accept, allowed)-def _hook_specs(cfg: Optional[dict[str, Any]]) -> Optional[list[ShellHookSpec]]:- """The configured hooks, or ``None`` when this process must run none (safe worker, safe mode,- no config) — the one guard every registrar and the consent path share."""+def accept_for_launch(cfg: Optional[dict[str, Any]]) -> None:+ """A launch's ``--accept-hooks`` on the gateway: record every configured hook in the allowlist,+ and keep the consent in memory until the allowlist holds it, so a failed write still registers+ the hook at the next ``sync_from_config`` (main registered it in memory)."""+ specs, _complete = _hook_specs(cfg)+ if not specs:+ return+ record_consent_from_config(cfg, accept_hooks=True)+ home_key = _home_key()+ with _sync_lock:+ _launch_consent.update((home_key, spec.event, spec.command) for spec in specs)+++def accept_for_process() -> None:+ """This process's own ``--accept-hooks`` (``hermes gateway run --accept-hooks``): an opt-in in+ force for its lifetime, as ``HERMES_ACCEPT_HOOKS`` would be, without exporting that variable to+ every tool subprocess."""+ global _process_accept+ _process_accept = True+++def _hook_specs(cfg: Optional[dict[str, Any]]) -> tuple[Optional[list[ShellHookSpec]], bool]:+ """``(specs, complete)``: the configured hooks, or ``None`` when this process must run none+ (safe worker, safe mode, no config) — the one guard every registrar and the consent path share;+ ``complete`` is False when a configured entry was dropped as malformed."""from agent.safe_worker_policy import safe_worker_enabledfrom utils import env_var_enabledif safe_worker_enabled() or not isinstance(cfg, dict):- return None+ return None, Trueif env_var_enabled("HERMES_SAFE_MODE"): # hooks are user customizations too — fire zero user-configured code- logger.debug("HERMES_SAFE_MODE=1 — shell-hook registration skipped")- return None- return _parse_hooks_block(cfg.get("hooks"))+ logger.info("HERMES_SAFE_MODE=1 — shell-hook registration skipped")+ return None, True+ return _parse_hooks(cfg.get("hooks"))+++def _key(home_key: str, spec: ShellHookSpec) -> tuple[str, str, Optional[str], str]:+ return (home_key, spec.event, spec.matcher, spec.command)def _wire(manager: Any, home_key: str, specs: list[ShellHookSpec]) -> list[ShellHookSpec]:"""Register ``specs`` not yet wired for this home; caller holds ``_registered_lock``."""registered = []for spec in specs:- key = (home_key, spec.event, spec.matcher, spec.command)+ key = _key(home_key, spec)if key in _registered:continuecallback = _make_callback(spec)@@ -236,15 +286,16 @@ def _wire(manager: Any, home_key: str, specs: list[ShellHookSpec]) -> list[Shellreturn registered-def _approved_pairs(approvals: list[Any]) -> set[tuple[Any, Any]]:- return {(e.get("event"), e.get("command")) for e in approvals if isinstance(e, dict)}+def _approved_pairs(approvals: list[Any]) -> set[tuple[str, str]]:+ return {(e["event"], e["command"]) for e in approvals+ if isinstance(e, dict) and isinstance(e.get("event"), str) and isinstance(e.get("command"), str)}-def _allowlisted_pairs() -> set[tuple[Any, Any]]:+def _allowlisted_pairs() -> set[tuple[str, str]]:return _approved_pairs(load_allowlist()["approvals"])-def _consented(spec: ShellHookSpec, accept: bool, allowed: set[tuple[Any, Any]]) -> bool:+def _consented(spec: ShellHookSpec, accept: bool, allowed: set[tuple[str, str]]) -> bool:"""Allowlisted, or approved now (opt-in or TTY prompt, recorded); ``allowed`` caches one read."""pair = (spec.event, spec.command)if pair in allowed:@@ -281,24 +332,38 @@ def re_register_config_hooks() -> None:def reset_for_tests() -> None:"""Test-only: clear the idempotence set."""+ global _process_acceptwith _registered_lock:_registered.clear()+ _launch_consent.clear()+ _skip_logged.clear()+ _process_accept = False# --- Config parsing ---def _parse_hooks_block(hooks_cfg: Any) -> list[ShellHookSpec]:"""Normalise ``hooks:`` into specs; malformed entries warn-and-skip, never raise."""+ return _parse_hooks(hooks_cfg)[0]+++def _parse_hooks(hooks_cfg: Any) -> tuple[list[ShellHookSpec], bool]:+ """``(specs, complete)``: ``complete`` is False when an entry was dropped as malformed (a typo+ must not read as a deliberate removal); an absent or empty ``hooks:`` is complete."""from hermes_cli.plugins import SHELL_UNSUPPORTED_HOOKS, VALID_HOOKS+ if hooks_cfg is None:+ return [], Trueif not isinstance(hooks_cfg, dict):- return []+ return [], Falsespecs: list[ShellHookSpec] = []+ complete = Truefor event_name, entries in hooks_cfg.items():if event_name in ("output_spill", "outbound"): # reserved non-event sub-sections under `hooks:`continueif event_name in SHELL_UNSUPPORTED_HOOKS: # _parse_response has no channel for these directives — refuse loudlylogger.warning("hook event %r is Python-plugin-only: shell hooks cannot return its directive, ""so this registration is refused rather than silently ignored", event_name)+ complete = Falsecontinueif event_name not in VALID_HOOKS:suggestion = difflib.get_close_matches(str(event_name), VALID_HOOKS, n=1, cutoff=0.6)@@ -306,14 +371,18 @@ def _parse_hooks_block(hooks_cfg: Any) -> list[ShellHookSpec]:logger.warning("unknown hook event %r in hooks: config — did you mean %r?", event_name, suggestion[0])else:logger.warning("unknown hook event %r in hooks: config (valid: %s)", event_name, ", ".join(sorted(VALID_HOOKS)))+ complete = Falsecontinueif entries is None:continueif not isinstance(entries, list):logger.warning("hooks.%s must be a list of hook definitions; got %s", event_name, type(entries).__name__)+ complete = Falsecontinue- specs.extend(filter(None, (_parse_single_entry(event_name, i, raw) for i, raw in enumerate(entries))))- return specs+ parsed = [_parse_single_entry(event_name, i, raw) for i, raw in enumerate(entries)]+ complete = complete and None not in parsed+ specs.extend(spec for spec in parsed if spec is not None)+ return specs, completedef _parse_single_entry(event: str, index: int, raw: Any) -> Optional[ShellHookSpec]:@@ -626,14 +695,15 @@ def load_allowlist() -> dict[str, Any]:def save_allowlist(data: dict[str, Any]) -> None:- """Atomic write; on OSError log and keep the in-process approval."""+ """Atomic write; on OSError log and carry on (the approval is not saved)."""p = allowlist_path()try:atomic_json_write(p, data, sort_keys=True, mode=0o600)except OSError as exc:- logger.warning("Failed to persist shell hook allowlist to %s: %s. The approval is in-memory for this run, "- "but the next startup will re-prompt (or skip registration on non-TTY runs without "- "--accept-hooks / HERMES_ACCEPT_HOOKS).", p, exc)+ logger.warning("Failed to persist shell hook allowlist to %s: %s. The approval is not saved: the next "+ "run re-prompts (non-TTY runs skip the hook) unless --accept-hooks / HERMES_ACCEPT_HOOKS "+ "/ hooks_auto_accept is in force; a gateway keeps a launch's --accept-hooks until it "+ "restarts.", p, exc)@contextmanager@@ -710,8 +780,9 @@ def _command_script_path(command: str) -> str:def _resolve_effective_accept(cfg: dict[str, Any], accept_hooks_arg: bool) -> bool:- """Any truthy opt-in channel wins: explicit arg, HERMES_ACCEPT_HOOKS, hooks_auto_accept."""- if accept_hooks_arg or os.environ.get("HERMES_ACCEPT_HOOKS", "").strip().lower() in _TRUTHY:+ """Any truthy opt-in channel wins: explicit arg, this process's --accept-hooks, HERMES_ACCEPT_HOOKS,+ hooks_auto_accept."""+ if accept_hooks_arg or _process_accept or os.environ.get("HERMES_ACCEPT_HOOKS", "").strip().lower() in _TRUTHY:return Truecfg_val = cfg.get("hooks_auto_accept", False)return cfg_val if isinstance(cfg_val, bool) else isinstance(cfg_val, str) and cfg_val.strip().lower() in _TRUTHYdiff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex a81103a9a7b..67ed4e49843 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -490,6 +490,8 @@ class AuthorityConnection:self.authority.authorize(self.actor, ref, 'session:control')from gateway.session_local_mcp import resume_editor_mcpresume_editor_mcp(self.authority, ref, params['editor'])+ if params.get('accept_hooks') is True: # consent recorded for the whole profile: a control+ self.authority.authorize(self.actor, ref, 'session:control')if 'api_key' in params:# A launch-only key re-supplied after a restart (`--resume <id> --api-key`).self.authority.authorize(self.actor, ref, 'session:control')@@ -507,7 +509,9 @@ class AuthorityConnection:source = self.authority.sessions[snapshot.handle.ref.session_id].sourceif source is not None and source.platform == Platform.LOCAL:from gateway.session_policy import policy_for_source, refresh_profile_hooks- await asyncio.to_thread(refresh_profile_hooks, policy_for_source(self.authority.runner, source))+ # `--resume <id> --accept-hooks`: this launch's consent, for hooks added since creation.+ await asyncio.to_thread(refresh_profile_hooks, policy_for_source(self.authority.runner, source),+ accept=params.get('accept_hooks') is True)info = await snapshot_info(self.authority, snapshot.handle.ref)display = {}if params.get('display_projection'):diff --git a/gateway/session_policy.py b/gateway/session_policy.pyindex fe204e0bcb0..329bc2c82f2 100644--- a/gateway/session_policy.py+++ b/gateway/session_policy.py@@ -527,29 +527,32 @@ def render_launch_skills(params, session_id):def accept_launch_hooks(policy):"""`--accept-hooks` / `HERMES_ACCEPT_HOOKS=1` on a launch: consent to the profile's configured- shell hooks in the per-user allowlist (no prompt). A bypass launch has no profile hooks to+ shell hooks in the per-user allowlist (no prompt; kept in memory if that write fails), which+ the open's ``refresh_profile_hooks`` then registers. A bypass launch has no profile hooks toconsent to, so the flag is a no-op there rather than a refusal. Allowlist I/O: off the loop."""if json.loads(policy.request_json).get('accept_hooks') and not policy.ignore_user_config:- from agent.shell_hooks import record_consent_from_config+ from agent.shell_hooks import accept_for_launchfrom gateway.run import _load_gateway_config- record_consent_from_config(_load_gateway_config(), accept_hooks=True)+ accept_for_launch(_load_gateway_config())-def refresh_profile_hooks(policy):+def refresh_profile_hooks(policy, *, accept=False):"""Bring this owner's shell hooks in step with the profile on every local session open(create and resume): hooks added to ``config.yaml`` or approved since the gateway startedregister, removed or revoked ones stop firing, as each new CLI process did on main. Reads theowner home's LIVE config (as session creation does), never the session's frozen copy: theregistry is shared by every session and surface of this profile. Consent comes from the- allowlist only (the launching client's TTY prompt, or ``accept_launch_hooks``); this never- prompts. A bypass launch registers nothing (main's safe mode registered none). Config read +- allowlist I/O: run off the loop."""+ allowlist (the launching client's TTY prompt, or ``accept_launch_hooks``) or an opt-in in force+ on the gateway itself; this never prompts. A bypass launch registers nothing (main's safe mode+ registered none). Config read + allowlist I/O: run off the loop."""if policy is None or policy.ignore_user_config:return- from agent.shell_hooks import sync_from_config+ from agent.shell_hooks import accept_for_launch, sync_from_configfrom gateway.run import _load_gateway_configtry:- sync_from_config(_load_gateway_config()) # it never removes on an empty (failed-open) config+ if accept: # a resuming launch's --accept-hooks (creation records it in accept_launch_hooks)+ accept_for_launch(_load_gateway_config())+ sync_from_config(_load_gateway_config) # it never removes on an empty (failed-open) configexcept Exception: # health: allow BLE001 -- best effort; a hook re-sync never blocks opening a sessionlogger.warning("shell-hook re-sync failed; keeping the registered hooks", exc_info=True)diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex f282a4f00d1..db8d14c6ef0 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -2985,14 +2985,13 @@ def _prepare_agent_startup(args) -> None:try:from hermes_cli.config import load_configfrom agent.shell_hooks import register_from_config+ from agent.outbound_webhooks import register_from_config as register_outbound_webhooks_hooks_cfg = load_config()register_from_config(_hooks_cfg, accept_hooks=_accept_hooks)-- from agent.outbound_webhooks import (- register_from_config as register_outbound_webhooks,- )-+ if _accept_hooks and args.command == "gateway": # every session-open re-sync keeps honouring it+ from agent.shell_hooks import accept_for_process+ accept_for_process()register_outbound_webhooks(_hooks_cfg)except Exception:logger.debug(diff --git a/tests/gateway/test_shell_hook_resync.py b/tests/gateway/test_shell_hook_resync.pyindex 90df6a21497..00b59d44778 100644--- a/tests/gateway/test_shell_hook_resync.py+++ b/tests/gateway/test_shell_hook_resync.py@@ -70,7 +70,7 @@ def test_gateway_resync_follows_config_and_allowlist_without_prompting(home, tmp# Unreadable inputs never disarm a guard: an empty config (the loader fails open to {}), or a# corrupt allowlist.- shell_hooks.sync_from_config({})+ shell_hooks.sync_from_config(dict)assert len(_wired()) == 2allowlist = home / shell_hooks.ALLOWLIST_FILENAMEsaved = allowlist.read_text()@@ -103,6 +103,76 @@ def test_gateway_resync_follows_config_and_allowlist_without_prompting(home, tmpassert _wired() == []+def test_resync_keeps_in_memory_consent_and_never_disarms_on_bad_input(home, tmp_path, monkeypatch):+ """Review of #139067: a launch's --accept-hooks survives a failed allowlist write; the gateway's+ own --accept-hooks covers hooks added later; a malformed hooks: entry or allowlist record+ never disarms a guard; an older snapshot never lands after a newer one."""+ import threading+ from gateway import run+ from gateway.session_policy import accept_launch_hooks, build_policy, refresh_profile_hooks+ a, b = _script(tmp_path, "a.sh"), _script(tmp_path, "b.sh")+ cfg = _cfg(a)+ monkeypatch.setattr(run, "_load_gateway_config", lambda: cfg)+ policy = build_policy({"source": "cli", "cwd": str(tmp_path)}, {})+ # Unwritable allowlist: the launch's consent is kept in memory, as main registered it.+ with monkeypatch.context() as unwritable:+ unwritable.setattr(shell_hooks, "atomic_json_write", lambda *a, **k: (_ for _ in ()).throw(OSError("ro")))+ accept_launch_hooks(build_policy({"source": "cli", "cwd": str(tmp_path), "accept_hooks": True}, {}))+ refresh_profile_hooks(policy)+ refresh_profile_hooks(policy)+ assert _wired() == [f"shell_hook[pre_tool_call:{a}]"]++ # A malformed entry (a list written as a mapping, or a bad record) adds but never removes.+ allowlist = home / shell_hooks.ALLOWLIST_FILENAME+ allowlist.write_text(json.dumps({"approvals": [{"event": "pre_tool_call", "command": []},+ {"event": "pre_tool_call", "command": b}]}))+ cfg["hooks"]["pre_tool_call"] = {"command": a}+ refresh_profile_hooks(policy)+ assert _wired() == [f"shell_hook[pre_tool_call:{a}]"]+ cfg["hooks"]["pre_tool_call"] = [{"command": a}, {"command": b}]+ refresh_profile_hooks(policy)+ assert len(_wired()) == 2++ # `gateway run --accept-hooks`: a hook added after start registers with no allowlist entry.+ c = _script(tmp_path, "c.sh")+ cfg["hooks"]["pre_tool_call"].append({"command": c})+ refresh_profile_hooks(policy)+ assert f"shell_hook[pre_tool_call:{c}]" not in _wired()+ shell_hooks.accept_for_process()+ refresh_profile_hooks(policy)+ assert f"shell_hook[pre_tool_call:{c}]" in _wired()+ shell_hooks.reset_for_tests()+ from hermes_cli import plugins+ plugins.get_plugin_manager()._hooks = {}++ # Ordering: a sync that read the old config first still applies before the newer one.+ old_read, release = threading.Event(), threading.Event()++ def stale():+ old_read.set()+ release.wait(5)+ return _cfg(a)++ first = threading.Thread(target=shell_hooks.sync_from_config, args=(stale,))+ first.start()+ old_read.wait(5)+ second = threading.Thread(target=shell_hooks.sync_from_config, args=(lambda: _cfg(b),))+ second.start()+ release.set()+ first.join(5)+ second.join(5)+ assert _wired() == [f"shell_hook[pre_tool_call:{b}]"]+++def test_register_never_reasks_for_a_wired_hook(home, tmp_path, monkeypatch):+ a = _script(tmp_path, "a.sh")+ shell_hooks.register_from_config(_cfg(a), accept_hooks=True)+ shell_hooks.revoke(a)+ monkeypatch.setattr(sys, "stdin", SimpleNamespace(isatty=lambda: True))+ monkeypatch.setattr("builtins.input", lambda *_: pytest.fail("re-prompted for a wired hook"))+ assert shell_hooks.register_from_config(_cfg(a)) == []++def test_classic_cli_asks_on_its_terminal_before_opening_the_session(home, tmp_path, monkeypatch):from hermes_cli import cli_init_mixinfrom hermes_cli.gateway_session_store import GatewaySessionStorediff --git a/ui-tui/src/__tests__/canonicalGateway.test.ts b/ui-tui/src/__tests__/canonicalGateway.test.tsindex d68c8dd95d7..99adbd72575 100644--- a/ui-tui/src/__tests__/canonicalGateway.test.ts+++ b/ui-tui/src/__tests__/canonicalGateway.test.ts@@ -32,6 +32,12 @@ it('carries -s/--checkpoints/--pass-session-id/--accept-hooks (and exported HERMexpect(canonicalRequest('session.create', { request_id: 'owned', ...options }, contract).params).toMatchObject(options)})+it('carries --accept-hooks onto session.resume for hooks configured since creation', () => {+ const resume = (env: Record<string, string>) => canonicalRequest('session.resume', { session_id: 'sid' }, undefined, env as NodeJS.ProcessEnv).params+ expect(resume({ HERMES_ACCEPT_HOOKS: '1' }).accept_hooks).toBe(true)+ expect(resume({ HERMES_ACCEPT_HOOKS: '0' })).not.toHaveProperty('accept_hooks')+})+it('rebuilds --max-turns from the launcher environment as the integer the session policy requires', () => {const options = localCreationOptions({ HERMES_TUI_MAX_TURNS: '5', HERMES_MODEL: 'local-model' } as NodeJS.ProcessEnv)expect(options.max_turns).toBe(5)diff --git a/ui-tui/src/canonicalGateway.ts b/ui-tui/src/canonicalGateway.tsindex 271b67429bb..837ca9c9724 100644--- a/ui-tui/src/canonicalGateway.ts+++ b/ui-tui/src/canonicalGateway.ts@@ -7,7 +7,9 @@ export const sharedControlParams = (prompt?: { sharedControl?: SharedControl } |export interface CreationContract { sources: string[]; parameters: string[] }-export function canonicalRequest(method: string, original: Record<string, unknown>, contract?: CreationContract) {+const truthy = (value?: string) => ['1', 'true', 'yes', 'on'].includes((value ?? '').trim().toLowerCase())++export function canonicalRequest(method: string, original: Record<string, unknown>, contract?: CreationContract, env = process.env) {const params = { ...original }if (method === 'session.create') {@@ -35,6 +37,10 @@ export function canonicalRequest(method: string, original: Record<string, unknowdelete params.omit_messagesif (renders) { params.display_projection = true }++ // `--resume <id> --accept-hooks`: hooks configured since the session was created need this+ // launch's consent too (session.create carries it in localCreationOptions).+ if (truthy(env.HERMES_ACCEPT_HOOKS)) { params.accept_hooks = true }}return { method, params }@@ -122,8 +128,6 @@ export function localCreationOptions(env = process.env): Record<string, unknown>// `hermes --tui --yolo` / `--ignore-rules` export HERMES_YOLO_MODE / HERMES_IGNORE_RULES (the in-process// TUI read them); over the canonical gateway they must ride session.create as frozen launch flags or the// session prompts anyway / still loads rules, SOUL, memory and skills.auto_load.- const truthy = (value?: string) => ['1', 'true', 'yes', 'on'].includes((value ?? '').trim().toLowerCase())-// `--checkpoints` / `--pass-session-id` / `--accept-hooks` (and an exported HERMES_ACCEPT_HOOKS=1)// are this session's creation policy too: the owner applies them, nothing reads them in-process.for (const [field, value] of [