Skip to content

The agent that grows with you

fix(hooks): drop resume accept_hooks; keep only unsaved launch consent; warn when removal is suspended

kshitijk4poor4b0d406f2c95
diff --git a/agent/shell_hooks.py b/agent/shell_hooks.py
index e8c70a6cecf..eb22d325434 100644
--- a/agent/shell_hooks.py
+++ b/agent/shell_hooks.py
@@ -52,8 +52,8 @@ _TOP_LEVEL_PAYLOAD_KEYS = {"tool_name", "args", "session_id", "parent_session_id
# per-tool under one event), home so multiplexed-gateway profiles can register identical triples.
_registered: set[tuple[str, str, Optional[str], str]] = set()
_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).
+# Non-POSIX fallback for allowlist read-modify-write; separate from _registered_lock so an allowlist
+# write never waits on (or nests inside) a registry update.
_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()
@@ -156,7 +156,7 @@ def register_from_config(cfg: Optional[dict[str, Any]], *, accept_hooks: bool =
manager, 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()
+ 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:
@@ -206,6 +206,12 @@ def sync_from_config(load_cfg: Callable[[], dict[str, Any]]) -> None:
with _registered_lock:
_wire(manager, home_key, wanted)
if not (readable and complete):
+ suspended = (home_key, "", "removal")
+ if suspended not in _skip_logged:
+ _skip_logged.add(suspended)
+ logger.warning("shell hooks: %s, so removed or revoked hooks stay registered until it is "
+ "fixed", "the allowlist is unreadable" if not readable
+ else "a hooks: entry in config.yaml is malformed")
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}
@@ -218,29 +224,29 @@ def sync_from_config(load_cfg: Callable[[], dict[str, Any]]) -> None:
logger.info("shell hook unregistered (removed from config or allowlist): %s -> %s", event, command)
-def record_consent_from_config(cfg: Optional[dict[str, Any]], *, accept_hooks: bool = False) -> None:
+def record_consent_from_config(cfg: Optional[dict[str, Any]], *, accept_hooks: bool = False) -> list[ShellHookSpec]:
"""First-use consent without registering anything, for a client whose turns run in a gateway that
has no TTY: the prompt (or an opt-in) for each configured hook not yet allowlisted. The gateway
- registers from the same allowlist when the client opens its session."""
+ registers from the same allowlist when the client opens its session. Returns the consented specs."""
specs, _complete = _hook_specs(cfg)
if not specs:
- return
- accept, allowed = _resolve_effective_accept(cfg, accept_hooks), _allowlisted_pairs()
- for spec in specs:
- _consented(spec, accept, allowed)
+ return []
+ accept, allowed = _resolve_effective_accept(cfg, accept_hooks), allowlisted_pairs()
+ return [spec for spec in specs if _consented(spec, accept, allowed)]
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)
+ and keep the consent in memory when that write fails, so it still registers
+ the hook at the next ``sync_from_config`` (main registered it in memory). Only an unsaved approval
+ is held, so a later ``hermes hooks revoke`` of a saved one takes effect."""
+ specs = record_consent_from_config(cfg, accept_hooks=True)
if not specs:
return
- record_consent_from_config(cfg, accept_hooks=True)
- home_key = _home_key()
+ saved, home_key = allowlisted_pairs(), _home_key()
with _sync_lock:
- _launch_consent.update((home_key, spec.event, spec.command) for spec in specs)
+ _launch_consent.update((home_key, spec.event, spec.command) for spec in specs
+ if (spec.event, spec.command) not in saved)
def accept_for_process() -> None:
@@ -291,7 +297,7 @@ def _approved_pairs(approvals: list[Any]) -> set[tuple[str, str]]:
if isinstance(e, dict) and isinstance(e.get("event"), str) and isinstance(e.get("command"), str)}
-def _allowlisted_pairs() -> set[tuple[str, str]]:
+def allowlisted_pairs() -> set[tuple[str, str]]:
return _approved_pairs(load_allowlist()["approvals"])
@@ -700,10 +706,9 @@ def save_allowlist(data: dict[str, Any]) -> None:
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 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)
+ logger.warning("Failed to persist shell hook allowlist to %s: %s. The approval holds for this process "
+ "only (a gateway keeps a launch's --accept-hooks until it restarts); a gateway session "
+ "opened from a CLI prompt skips the hook, and the next run re-prompts.", p, exc)
@contextmanager
@@ -759,7 +764,8 @@ def _record_approval(event: str, command: str) -> None:
def revoke(command: str) -> int:
"""Remove every allowlist entry for ``command``; returns the count. A gateway unregisters it at its
- next local session open (``sync_from_config``); other live processes keep it until restart."""
+ next local session open (``sync_from_config``) unless an opt-in approves every hook; other live
+ processes keep it until restart."""
with _locked_update_approvals() as data:
before = len(data.get("approvals", []))
data["approvals"] = [e for e in data.get("approvals", []) if not _entry_matches(e, None, command)]
@@ -782,7 +788,8 @@ 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, 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:
+ from utils import env_var_enabled
+ if accept_hooks_arg or _process_accept or env_var_enabled("HERMES_ACCEPT_HOOKS"):
return True
cfg_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 _TRUTHY
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index 67ed4e49843..a81103a9a7b 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -490,8 +490,6 @@ class AuthorityConnection:
self.authority.authorize(self.actor, ref, 'session:control')
from gateway.session_local_mcp import resume_editor_mcp
resume_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')
@@ -509,9 +507,7 @@ class AuthorityConnection:
source = self.authority.sessions[snapshot.handle.ref.session_id].source
if source is not None and source.platform == Platform.LOCAL:
from gateway.session_policy import policy_for_source, refresh_profile_hooks
- # `--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)
+ await asyncio.to_thread(refresh_profile_hooks, policy_for_source(self.authority.runner, source))
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.py
index 329bc2c82f2..f0f7df3fa66 100644
--- a/gateway/session_policy.py
+++ b/gateway/session_policy.py
@@ -536,7 +536,7 @@ def accept_launch_hooks(policy):
accept_for_launch(_load_gateway_config())
-def refresh_profile_hooks(policy, *, accept=False):
+def refresh_profile_hooks(policy):
"""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 started
register, removed or revoked ones stop firing, as each new CLI process did on main. Reads the
@@ -547,11 +547,9 @@ def refresh_profile_hooks(policy, *, accept=False):
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 accept_for_launch, sync_from_config
+ from agent.shell_hooks import sync_from_config
from gateway.run import _load_gateway_config
try:
- 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) config
except Exception: # health: allow BLE001 -- best effort; a hook re-sync never blocks opening a session
logger.warning("shell-hook re-sync failed; keeping the registered hooks", exc_info=True)
diff --git a/hermes_cli/hooks.py b/hermes_cli/hooks.py
index 1318d3f53fa..32a15326340 100644
--- a/hermes_cli/hooks.py
+++ b/hermes_cli/hooks.py
@@ -46,11 +46,7 @@ def _cmd_list(_args) -> None:
by_event: dict[str, list] = {}
for spec in specs:
by_event.setdefault(spec.event, []).append(spec)
- approved = {
- (e.get("event"), e.get("command"))
- for e in shell_hooks.load_allowlist().get("approvals", [])
- if isinstance(e, dict)
- }
+ approved = shell_hooks.allowlisted_pairs()
print(f"Configured shell hooks ({len(specs)} total):\n")
for event in sorted(by_event):
print(f" [{event}]")
@@ -263,7 +259,8 @@ def _cmd_revoke(args) -> None:
return
print(f"Removed {removed} allowlist entry/entries for: {args.command}")
print(
- "Note: a running gateway stops running it when the next local session opens; "
+ "Note: a running gateway stops running it when the next local session opens (unless "
+ "--accept-hooks / HERMES_ACCEPT_HOOKS / hooks_auto_accept approves every hook there); "
"other running processes keep it until they restart."
)
diff --git a/tests/gateway/test_shell_hook_resync.py b/tests/gateway/test_shell_hook_resync.py
index 00b59d44778..42c5af68660 100644
--- a/tests/gateway/test_shell_hook_resync.py
+++ b/tests/gateway/test_shell_hook_resync.py
@@ -105,8 +105,9 @@ def test_gateway_resync_follows_config_and_allowlist_without_prompting(home, tmp
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."""
+ own --accept-hooks covers hooks added later; a malformed hooks: entry never disarms a guard and
+ a malformed allowlist record never breaks the valid ones; 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
@@ -164,6 +165,18 @@ def test_resync_keeps_in_memory_consent_and_never_disarms_on_bad_input(home, tmp
assert _wired() == [f"shell_hook[pre_tool_call:{b}]"]
+def test_saved_launch_approval_stays_revocable_and_bad_records_are_skipped(home, tmp_path):
+ a, b = _script(tmp_path, "a.sh"), _script(tmp_path, "b.sh")
+ shell_hooks.accept_for_launch(_cfg(a)) # saved, so not held in memory
+ shell_hooks.revoke(a) # before any session open
+ shell_hooks.sync_from_config(lambda: _cfg(a))
+ assert _wired() == []
+ (home / shell_hooks.ALLOWLIST_FILENAME).write_text(json.dumps({"approvals": [
+ {"event": "pre_tool_call", "command": []}, {"event": "pre_tool_call", "command": b}]}))
+ shell_hooks.sync_from_config(lambda: _cfg(b))
+ 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)
diff --git a/ui-tui/src/__tests__/canonicalGateway.test.ts b/ui-tui/src/__tests__/canonicalGateway.test.ts
index 99adbd72575..d68c8dd95d7 100644
--- a/ui-tui/src/__tests__/canonicalGateway.test.ts
+++ b/ui-tui/src/__tests__/canonicalGateway.test.ts
@@ -32,12 +32,6 @@ it('carries -s/--checkpoints/--pass-session-id/--accept-hooks (and exported HERM
expect(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.ts
index 837ca9c9724..271b67429bb 100644
--- a/ui-tui/src/canonicalGateway.ts
+++ b/ui-tui/src/canonicalGateway.ts
@@ -7,9 +7,7 @@ export const sharedControlParams = (prompt?: { sharedControl?: SharedControl } |
export interface CreationContract { sources: string[]; parameters: string[] }
-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) {
+export function canonicalRequest(method: string, original: Record<string, unknown>, contract?: CreationContract) {
const params = { ...original }
if (method === 'session.create') {
@@ -37,10 +35,6 @@ export function canonicalRequest(method: string, original: Record<string, unknow
delete params.omit_messages
if (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 }
@@ -128,6 +122,8 @@ 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 [