Skip to content

The agent that grows with you

fix(worker): ordinary managed runs register the session's shell hooks and webhooks

Tekniumfcc895496eb8
diff --git a/agent/managed_worker.py b/agent/managed_worker.py
index a7aa4a9906d..e8d1e5f0d6c 100644
--- a/agent/managed_worker.py
+++ b/agent/managed_worker.py
@@ -294,8 +294,9 @@ def execute(frame, channel):
from tools.process_registry import process_registry
process_registry.recover_from_checkpoint()
# Store construction binds the delegation ledger before tool discovery.
- from gateway.session_policy import restore_policy, policy_scope
+ from gateway.session_policy import restore_policy, policy_scope, register_worker_hooks
policy = restore_policy(frame['policy'])
+ register_worker_hooks(policy)
discover_profile_mcp(policy)
from run_agent import AIAgent
from tools.approval import register_gateway_notify, unregister_gateway_notify
diff --git a/gateway/session_kanban.py b/gateway/session_kanban.py
index ec33dff6743..cab0d8d3b1b 100644
--- a/gateway/session_kanban.py
+++ b/gateway/session_kanban.py
@@ -175,8 +175,6 @@ def bind_worker_context(frame):
_watch_submitter(Path(context['db']), context['run_id'])
os.environ.update(env)
os.chdir(context['workspace'])
- from agent.shell_hooks import register_from_config
- register_from_config(json.loads(frame['policy']['config_json']), accept_hooks=context['accept_hooks'])
_TURNS_DONE = threading.Event()
diff --git a/gateway/session_policy.py b/gateway/session_policy.py
index b8dacd0b6eb..3cfdf26ecc2 100644
--- a/gateway/session_policy.py
+++ b/gateway/session_policy.py
@@ -278,6 +278,23 @@ def accept_launch_hooks(policy):
register_from_config(policy.config(), accept_hooks=True)
+def register_worker_hooks(policy):
+ """Worker side of the same contract: tools run in the managed child, so its own plugin
+ manager needs the session's shell hooks and outbound webhooks, registered from the frozen
+ config with the launch's consent (a Kanban attempt always consents), as the classic one-shot
+ CLI registered both at startup. Bypass sessions register nothing (the safe policy also
+ refuses inside both registrars)."""
+ if policy.ignore_user_config:
+ return
+ kanban = json.loads(policy.kanban_json or 'null') or {}
+ accept = json.loads(policy.request_json).get('accept_hooks') is True or kanban.get('accept_hooks') is True
+ from agent.outbound_webhooks import register_from_config as register_outbound_webhooks
+ from agent.shell_hooks import register_from_config
+ config = policy.config()
+ register_from_config(config, accept_hooks=accept)
+ register_outbound_webhooks(config)
+
+
def bind_launch_key(authority, session_id, policy, api_key, *, config_secrets=None):
"""CLI keys live only in this authority lifetime, never its durable receipt.
diff --git a/tests/gateway/test_managed_worker_construct.py b/tests/gateway/test_managed_worker_construct.py
index 0a05208b5aa..9cd70dd0138 100644
--- a/tests/gateway/test_managed_worker_construct.py
+++ b/tests/gateway/test_managed_worker_construct.py
@@ -73,7 +73,7 @@ def _serve(cls):
return server
-def run_pair(tmp_path, extra_config, turn):
+def run_pair(tmp_path, extra_config, turn, **create_params):
"""Boot one ordinary daemon; create an in-process and a managed session from the same config;
run ``turn(ws, sid, name, settle, servers)`` for each and return its results by session."""
root = Path(__file__).resolve().parents[2]
@@ -117,7 +117,7 @@ def run_pair(tmp_path, extra_config, turn):
(home / 'config.yaml').write_text(json.dumps(edited))
created = await rpc(ws, 'session.create', request_id=name, source='cli', cwd=str(home),
model='primary-model', provider='custom', base_url=purl,
- api_key='loopback-only', toolsets=[])
+ api_key='loopback-only', toolsets=[], **create_params)
assert 'result' in created, created
sid = created['result']['session_id']
results[name] = await turn(ws, sid, name, settle, SimpleNamespace(primary=primary, backup=backup, query=query))
diff --git a/tests/gateway/test_managed_worker_hooks.py b/tests/gateway/test_managed_worker_hooks.py
new file mode 100644
index 00000000000..77c08989f14
--- /dev/null
+++ b/tests/gateway/test_managed_worker_hooks.py
@@ -0,0 +1,74 @@
+"""Ordinary managed runs register the session's shell hooks and outbound webhooks in the worker,
+where tools and model calls actually run (unsupportedpastels §2.4); bypass sessions register none.
+"""
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+import json
+import threading
+
+import pytest
+
+from tests.gateway.test_managed_worker_construct import run_pair
+
+
+class Receiver(BaseHTTPRequestHandler):
+ def log_message(self, *args):
+ pass
+
+ def do_POST(self):
+ self.server.deliveries.append(json.loads(self.rfile.read(int(self.headers['Content-Length']))))
+ self.send_response(204)
+ self.end_headers()
+
+
+def test_managed_turn_fires_shell_hooks_and_webhooks_in_the_worker(tmp_path):
+ receiver = ThreadingHTTPServer(('127.0.0.1', 0), Receiver)
+ receiver.deliveries = []
+ threading.Thread(target=receiver.serve_forever, daemon=True).start()
+ fired = tmp_path / 'state' / 'hook-fired.log'
+
+ def extra(home):
+ # No auto-accept: consent comes from the session's own `--accept-hooks` launch flag.
+ return {'hooks': {'pre_llm_call': [{'command': f'sh -c "echo $PPID >> {fired}"'}],
+ 'outbound': [{'url': f'http://127.0.0.1:{receiver.server_port}/h', 'events': ['pre_llm_call']}]}}
+
+ async def turn(ws, sid, name, settle, servers):
+ before_fires = fired.read_text().split() if fired.exists() else []
+ before_hooks = len(receiver.deliveries)
+ assert (await settle(ws, sid, name + '-plain', 'PLAIN_TURN'))['final_response'] == 'PRIMARY_OK'
+ after = fired.read_text().split() if fired.exists() else []
+ return {'shell_pids': after[len(before_fires):],
+ 'webhooks': [d['hook_event_name'] for d in receiver.deliveries[before_hooks:]]}
+ try:
+ results = run_pair(tmp_path, extra, turn, accept_hooks=True)
+ finally:
+ receiver.shutdown()
+ receiver.server_close()
+ for name in ('inproc', 'managed'):
+ assert len(results[name]['shell_pids']) == 1, results
+ assert results[name]['webhooks'] and set(results[name]['webhooks']) == {'pre_llm_call'}, results
+ # The managed turn's hook ran in its own worker interpreter, not the owner.
+ assert results['managed']['shell_pids'] != results['inproc']['shell_pids'], results
+
+
+def test_worker_hook_registration_follows_the_session_policy(tmp_path, monkeypatch):
+ from gateway.session_local import _bypass_policy
+ from gateway.session_policy import build_policy, register_worker_hooks
+ calls = []
+ monkeypatch.setattr('agent.shell_hooks.register_from_config',
+ lambda cfg, accept_hooks=False: calls.append(('shell', cfg['hooks'], accept_hooks)))
+ monkeypatch.setattr('agent.outbound_webhooks.register_from_config',
+ lambda cfg: calls.append(('outbound', cfg['hooks'])))
+ hooks = {'pre_llm_call': [{'command': 'true'}]}
+ launch = {'cwd': str(tmp_path), 'model': 'm', 'provider': 'custom', 'base_url': 'http://127.0.0.1:9/v1'}
+ register_worker_hooks(build_policy(launch, {'hooks': hooks}))
+ register_worker_hooks(build_policy({**launch, 'accept_hooks': True}, {'hooks': hooks}))
+ kanban = build_policy(launch, {'hooks': hooks})
+ from dataclasses import replace
+ register_worker_hooks(replace(kanban, kanban_json=json.dumps({'accept_hooks': True})))
+ assert calls == [('shell', hooks, False), ('outbound', hooks), ('shell', hooks, True), ('outbound', hooks),
+ ('shell', hooks, True), ('outbound', hooks)]
+ calls.clear()
+ for bypass in ({'ignore_user_config': True}, {'safe_mode': True}):
+ register_worker_hooks(_bypass_policy({**launch, **bypass, 'accept_hooks': True}, private_secrets={}))
+ assert calls == []