The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): honor configured shell hooks for each chat profile
Teknium3094cde5138b
diff --git a/evals/desktop_bug_campaign/hooks_live.py b/evals/desktop_bug_campaign/hooks_live.pynew file mode 100644index 00000000000..a7cac4956c3--- /dev/null+++ b/evals/desktop_bug_campaign/hooks_live.py@@ -0,0 +1,132 @@+"""Real serve + WebSocket + local HTTP inference fixture hook probe (no vendor calls)."""+import argparse+import json+import os+from pathlib import Path+import shlex+import subprocess+import sys+import threading+import time+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer++import yaml+from websockets.sync.client import connect++p = argparse.ArgumentParser()+p.add_argument('--output', required=True)+p.add_argument('--port', type=int, default=18000)+p.add_argument('--tool', choices=['write_file', 'terminal'], default='write_file')+p.add_argument('--repo', type=Path, default=Path(__file__).resolve().parents[2])+a = p.parse_args()+out = Path(a.output).absolute()+out.mkdir(parents=True, exist_ok=True)+home = out / 'home'+home.mkdir(exist_ok=True)+requests = []+++class Provider(BaseHTTPRequestHandler):+ def log_message(self, *_args):+ pass++ def do_POST(self):+ req = json.loads(self.rfile.read(int(self.headers['Content-Length'])))+ requests.append(req)+ messages = req.get('messages', [])+ last_user = next((m['content'] for m in reversed(messages) if m['role'] == 'user'), '')+ label = next((x for x in ['alpha', 'beta', 'default', 'unapproved'] if x in str(last_user)), 'default')+ tool_seen = any(m['role'] == 'tool' for m in messages)+ target = str(out / (label + '-protected.txt'))+ tool_args = ({'path': target, 'content': 'UNGUARDED'} if a.tool == 'write_file' else {+ 'command': f'printf %s UNGUARDED > {shlex.quote(target)}'})+ delta = {'role': 'assistant', 'content': 'fixture complete'} if tool_seen or not req.get('tools') else {+ 'role': 'assistant', 'tool_calls': [{'index': 0, 'id': 'call_probe', 'type': 'function', 'function': {+ 'name': a.tool, 'arguments': json.dumps(tool_args)}}]}+ finish = 'stop' if 'content' in delta else 'tool_calls'+ self.send_response(200)+ self.send_header('Content-Type', 'text/event-stream' if req.get('stream') else 'application/json')+ self.end_headers()+ if req.get('stream'):+ for d, f in [(delta, None), ({}, finish)]:+ self.wfile.write(('data: ' + json.dumps({'id': 'fixture', 'object': 'chat.completion.chunk', 'choices': [{'index': 0, 'delta': d, 'finish_reason': f}]}) + '\n\n').encode())+ self.wfile.write(b'data: [DONE]\n\n')+ else:+ delta.pop('index', None)+ for tc in delta.get('tool_calls', []):+ tc.pop('index', None)+ self.wfile.write(json.dumps({'id': 'fixture', 'object': 'chat.completion', 'choices': [{'index': 0, 'message': delta, 'finish_reason': finish}], 'usage': {'prompt_tokens': 100, 'completion_tokens': 10}}).encode())+++provider = ThreadingHTTPServer(('127.0.0.1', a.port + 1), Provider)+threading.Thread(target=provider.serve_forever, daemon=True).start()+for label in ['default', 'alpha', 'beta', 'unapproved']:+ h = home if label == 'default' else home / 'profiles' / label+ h.mkdir(parents=True, exist_ok=True)+ hook = h / 'guard.py'+ hook.write_text('import json,sys\nfrom pathlib import Path\npayload=json.load(sys.stdin)\nwith Path(' + repr(str(out / (label + '-hooks.jsonl'))) + ').open("a") as f: f.write(json.dumps(payload)+"\\n")\nprint(json.dumps({"decision":"block","reason":' + repr('guard-' + label) + '}))\n')+ cfg = {'model': {'default': 'fixture-model', 'provider': 'custom', 'base_url': f'http://127.0.0.1:{a.port+1}/v1', 'api_key': 'fixture-key'},+ 'hooks_auto_accept': label != 'unapproved', 'hooks': {'pre_tool_call': [{'command': shlex.join([sys.executable, str(hook)]), 'matcher': a.tool, 'fail_closed': True}]},+ 'toolsets': ['file', 'terminal'], 'agent': {'max_turns': 3}, 'memory': {'memory_enabled': False, 'user_profile_enabled': False},+ 'curator': {'enabled': False}, 'compression': {'enabled': False}, 'terminal': {'cwd': str(out)}}+ (h / 'config.yaml').write_text(yaml.safe_dump(cfg))+ (h / '.env').write_text('OPENAI_API_KEY=fixture-key\nOPENAI_BASE_URL=http://127.0.0.1:' + str(a.port+1) + '/v1\n')+env = {k: v for k, v in os.environ.items() if not (k.startswith('HERMES_') or k.endswith(('_API_KEY', '_TOKEN')))}+env.update(HOME=str(out / 'os-home'), HERMES_HOME=str(home), HERMES_DASHBOARD_SESSION_TOKEN='hooks-fixture-token', HERMES_IGNORE_RULES='1', PYTHONPATH=str(a.repo))+cmd = [sys.executable, '-m', 'hermes_cli.main', 'serve', '--host', '127.0.0.1', '--port', str(a.port), '--skip-build']+log = (out / 'serve.log').open('w')+proc = subprocess.Popen(cmd, cwd=a.repo, env=env, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)+events = []+results = []+try:+ deadline = time.monotonic() + 90+ while True:+ try:+ ws = connect(f'ws://127.0.0.1:{a.port}/api/ws?token=hooks-fixture-token', open_timeout=2)+ break+ except Exception:+ if time.monotonic() > deadline or proc.poll() is not None:+ raise RuntimeError('serve failed to become ready')+ time.sleep(.3)+ serial = 0+ def rpc(method, params):+ global serial+ serial += 1+ rid = str(serial)+ ws.send(json.dumps({'jsonrpc': '2.0', 'id': rid, 'method': method, 'params': params}))+ while True:+ event = json.loads(ws.recv(timeout=90))+ events.append(event)+ if str(event.get('id')) == rid:+ if 'error' in event:+ raise RuntimeError(event)+ return event['result']+ for label in ['default', 'alpha', 'beta', 'alpha', 'unapproved']:+ session = rpc('session.create', {'source': 'gui', 'profile': '' if label == 'default' else label, 'cwd': str(out)})+ sid = session['session_id']+ rpc('prompt.submit', {'session_id': sid, 'text': f'{label} probe: write the protected file'})+ deadline = time.monotonic() + 100+ while time.monotonic() < deadline:+ event = json.loads(ws.recv(timeout=100))+ events.append(event)+ data = event.get('params', {})+ if data.get('type') in ('turn.complete', 'message.complete', 'agent.error', 'turn.error'):+ break+ results.append({'profile': label, 'written': (out / (label + '-protected.txt')).exists(), 'hook_calls': len((out / (label + '-hooks.jsonl')).read_text().splitlines()) if (out / (label + '-hooks.jsonl')).exists() else 0})+ print(results[-1], flush=True)+ ws.close()+ assert all(not row['written'] and row['hook_calls'] > 0 for row in results if row['profile'] != 'unapproved'), 'consented profile hook did not protect write_file'+ assert results[-1]['written'] and results[-1]['hook_calls'] == 0, 'unapproved hook executed'+finally:+ proc.terminate()+ try:+ proc.wait(timeout=15)+ except subprocess.TimeoutExpired:+ proc.kill()+ proc.wait()+ provider.shutdown()+ (out / 'events.json').write_text(json.dumps(events, indent=2))+ (out / 'requests.json').write_text(json.dumps(requests, indent=2))+ receipt = {'sha': subprocess.check_output(['git', '-C', str(a.repo), 'rev-parse', 'HEAD'], stdin=subprocess.DEVNULL, text=True).strip(), 'command': cmd, 'results': results, 'provider_requests': len(requests)}+ (out / 'receipt.json').write_text(json.dumps(receipt, indent=2))+ print(json.dumps(receipt, indent=2))diff --git a/tests/tui_gateway/test_profile_shell_hooks.py b/tests/tui_gateway/test_profile_shell_hooks.pynew file mode 100644index 00000000000..5530bd985fc--- /dev/null+++ b/tests/tui_gateway/test_profile_shell_hooks.py@@ -0,0 +1,53 @@+"""Profile-bound agent construction must arm real shell policy."""+import os+import shlex+import subprocess+import sys+from pathlib import Path++import yaml+++def test_agent_build_arms_only_consented_profile_policy(tmp_path, monkeypatch):+ from agent import shell_hooks+ from hermes_cli import plugins+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override+ from tui_gateway import server++ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ monkeypatch.setenv('HOME', str(tmp_path / 'os-home'))+ monkeypatch.setattr(Path, 'home', lambda: tmp_path / 'os-home')+ monkeypatch.setenv('HERMES_IGNORE_RULES', '1')+ monkeypatch.delenv('HERMES_ACCEPT_HOOKS', raising=False)+ monkeypatch.setattr(server, '_hermes_home', tmp_path)+ monkeypatch.setattr(server, '_get_db', lambda: None)+ # Only provider resolution is a fixture; registration, agent, hook process,+ # consent, manager selection and public dispatch are the real implementation.+ monkeypatch.setattr(server, '_resolve_agent_model_runtime', lambda *_a: (+ 'fixture-model', {'provider': 'openai-compat', 'base_url': 'http://127.0.0.1:18019/v1', 'api_key': 'fixture-key'}))+ plugins._reset_plugin_managers_for_tests()+ shell_hooks.reset_for_tests()+ try:+ for label, consent in [('alpha', True), ('beta', True), ('unapproved', False)]:+ home = tmp_path / label+ home.mkdir()+ script = home / 'guard.py'+ script.write_text('import json\nprint(json.dumps({"decision":"block","reason":' + repr(label) + '}))\n', encoding='utf-8')+ quote_command = subprocess.list2cmdline if os.name == 'nt' else shlex.join+ cfg = {'hooks_auto_accept': consent, 'hooks': {'pre_tool_call': [{+ 'command': quote_command([sys.executable, str(script)]), 'matcher': 'write_file', 'fail_closed': True}]},+ 'toolsets': ['file'], 'memory': {'memory_enabled': False, 'user_profile_enabled': False}}+ (home / 'config.yaml').write_text(yaml.safe_dump(cfg), encoding='utf-8')+ for label in ['alpha', 'beta', 'alpha', 'unapproved']:+ token = set_hermes_home_override(tmp_path / label)+ try:+ agent = server._make_agent(label, label, context_cwd_is_launch_artifact=False)+ assert agent is not None+ block = plugins.get_pre_tool_call_block_message('write_file', {'path': str(tmp_path / 'protected'), 'content': 'x'})+ assert block == (None if label == 'unapproved' else label)+ assert plugins.get_pre_tool_call_block_message('read_file', {'path': str(tmp_path / 'protected')}) is None+ finally:+ reset_hermes_home_override(token)+ finally:+ plugins._reset_plugin_managers_for_tests()+ shell_hooks.reset_for_tests()diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 6849dcb0237..54947e604ed 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -2275,6 +2275,9 @@ def _make_agent(with contextlib.suppress(Exception):importlib.import_module(_mod).wait_for_mcp_discovery()cfg = _load_cfg()+ # Agent creation already holds the session's profile scope, unlike serve startup.+ from agent.shell_hooks import register_from_config+ register_from_config(cfg)system_prompt = _startup_system_prompt(cfg, session_id or key)model, runtime = _resolve_agent_model_runtime(model_override, provider_override)_pr = _load_provider_routing()diff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.mdindex 75c28a6407a..8c6c773b25d 100644--- a/website/docs/user-guide/features/hooks.md+++ b/website/docs/user-guide/features/hooks.md@@ -12,7 +12,7 @@ Hermes has four hook systems that run custom code at key lifecycle points:|--------|---------------|---------|----------|| **[Gateway hooks](#gateway-event-hooks)** | `HOOK.yaml` + `handler.py` in `~/.hermes/hooks/` | Gateway only | Logging, alerts, webhooks || **[Plugin hooks](#plugin-hooks)** | `ctx.register_hook()` in a [plugin](/user-guide/features/plugins) | CLI + Gateway | Tool interception, metrics, guardrails |-| **[Shell hooks](#shell-hooks)** | `hooks:` block in `~/.hermes/config.yaml` pointing at shell scripts | CLI + Gateway | Drop-in scripts for blocking, auto-formatting, context injection |+| **[Shell hooks](#shell-hooks)** | `hooks:` block in profile `config.yaml` pointing at shell scripts | CLI + Gateway + Desktop/TUI/dashboard chat | Drop-in scripts for blocking, auto-formatting, context injection || **[Outbound webhooks](#outbound-webhooks)** | `hooks.outbound:` list in `~/.hermes/config.yaml` | CLI + Gateway | Push signed lifecycle events to external HTTP endpoints — CI, dashboards, other agents |Hook callback errors are isolated and logged rather than crashing the agent. Hooks are not all passive: directive/control hooks can change flow, transforms can replace content, and a shell `pre_tool_call` hook can block or fail closed.@@ -1577,7 +1577,9 @@ Five additional observers (RFC #58548) extend the kanban family. All are observe## Shell Hooks-Declare shell-script hooks in your `~/.hermes/config.yaml` and Hermes will run them as subprocesses whenever the corresponding plugin-hook event fires — in both CLI and gateway sessions. No Python plugin authoring required.+Declare shell-script hooks in your profile's `config.yaml` and Hermes will run them as subprocesses whenever the corresponding plugin-hook event fires — in CLI, gateway, Desktop, TUI, and dashboard chat sessions. No Python plugin authoring required.++Desktop, TUI, and dashboard chat register hooks when building an agent, using that session's profile configuration and consent allowlist. Switching profiles does not reuse another profile's hooks. Existing hook consent requirements and safe-mode behavior still apply; unapproved hooks are skipped rather than silently approved.Use shell hooks when you want a drop-in, single-file script (Bash, Python, anything with a shebang) to: