The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(approval): keep the execute_code gate for injected turns in a local session
unsupportedpastels021468f4b30e
diff --git a/gateway/session_ingress.py b/gateway/session_ingress.pyindex e51a2c31ab7..ffe8c6b29b1 100644--- a/gateway/session_ingress.py+++ b/gateway/session_ingress.py@@ -13,6 +13,8 @@ logger = logging.getLogger(__name__)admission_author = ContextVar('admission_author', default=None)executing_admission = ContextVar('executing_admission', default=False)+# The live session while the executing turn is one its viewer submitted (``is_viewer_input``), else None.+viewer_turn = ContextVar('viewer_turn', default=None)# Set by a busy-path caller that must be released once its input is durably queued.busy_acceptance = ContextVar('busy_acceptance', default=None)# ``_validate_native`` clauses about the message's own content, safe to name to the sender's chat.@@ -241,6 +243,8 @@ async def execute_admission(authority, ref, row):is_api = live.source.platform == Platform.API_SERVERauthor = event.metadata.get('turn_author')author_token = admission_author.set(author if author is not None else row_turn_author(local_policy, row))+ from gateway.session_operator import is_viewer_input+ viewer_token = viewer_turn.set(live if is_viewer_input(row) else None)api_token = api_execution.set(None)captured = {}result_token = execution_result.set(captured)@@ -301,6 +305,7 @@ async def execute_admission(authority, ref, row):execution_result.reset(result_token)api_execution.reset(api_token)admission_author.reset(author_token)+ viewer_turn.reset(viewer_token)async def _execution_scope(authority, home):diff --git a/gateway/session_operator.py b/gateway/session_operator.pyindex 19c2f94f973..40d411e755b 100644--- a/gateway/session_operator.py+++ b/gateway/session_operator.py@@ -7,10 +7,22 @@ public submission parameters cannot supply it."""from hermes_state_runtime import RuntimeStoreError+# Fields ``SessionAuthority.submit`` commits for a local session's input; producers commit their own envelope.+LOCAL_INPUT_FIELDS = frozenset({'text', 'attachments_v1', 'finite', 'unattended', 'surface_v1', 'display_v1',+ 'cli_turn_v1'})+++def is_viewer_input(row):+ """A row a session viewer submitted through ``session.submit`` (a client's own prompt), not a producer+ admission: ``local_automation_v1`` (plugin injection, delegation completions, process and watch notices,+ /loop, heartbeat), a hosted-room task (``hosted:`` request id) or any other envelope."""+ return (not str(row['request_id']).startswith('hosted:')+ and {'text'} <= set(row['payload']) <= LOCAL_INPUT_FIELDS | {'local_operator_v1'})+def check_local_input(authority, ref, row, *, source=None):payload = row['payload']- allowed = {'text', 'attachments_v1', 'finite', 'unattended', 'surface_v1', 'display_v1', 'cli_turn_v1'}+ allowed = set(LOCAL_INPUT_FIELDS)if 'local_operator_v1' in payload:allowed.add('local_operator_v1')if payload['local_operator_v1'] != {diff --git a/tests/gateway/test_local_turn_origin_execute_code_gate.py b/tests/gateway/test_local_turn_origin_execute_code_gate.pynew file mode 100644index 00000000000..7bee8e11a6b--- /dev/null+++ b/tests/gateway/test_local_turn_origin_execute_code_gate.py@@ -0,0 +1,108 @@+"""Which turns of a local session skip the whole-script ``execute_code`` approval (T2).++Only a turn the session's viewer submitted (``session.submit``) follows the interactive-CLI rule. A+plugin ``inject_message`` admission, a /loop tick or any other producer admission into the same+session keeps the whole-script gate: a script's ``shutil``/``subprocess`` calls never pass through a+``terminal()`` prompt. The turns run through the real FIFO drain (``execute_admission``); the handler+checks the gate the way the turn's agent thread does.+"""+import asyncio++import pytest++from tests.waiting import async_wait_until+++async def test_only_the_viewers_own_turn_skips_the_whole_script_gate(tmp_path, monkeypatch):+ from gateway.config import GatewayConfig+ from gateway.run import GatewayRunner+ from gateway.session_authority import initialize_session_authority+ from gateway.session_automation import admit_route_wake+ from gateway.session_context import clear_session_vars, set_session_vars+ from gateway.session_contract import Principal, Submission+ from gateway.session_local import create_local_session+ from gateway.session_policy import _ACTIVE_POLICY, policy_for_source+ from hermes_state import SessionDB+ from tools import approval as A+ from tools import approval_context++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setenv("HERMES_EXEC_ASK", "1") # start_gateway() sets it process-wide+ for name in ("HERMES_INTERACTIVE", "HERMES_GATEWAY_SESSION", "HERMES_CRON_SESSION"):+ monkeypatch.delenv(name, raising=False)+ monkeypatch.setattr(approval_context, "_get_approval_mode", lambda: "manual")+ monkeypatch.setattr(A, "_YOLO_MODE_FROZEN", False)+ runner = GatewayRunner(GatewayConfig(sessions_dir=tmp_path / "sessions"))+ db = SessionDB(tmp_path / "state.db")+ runner.session_store._db = runner._session_db = db+ authority = await initialize_session_authority(runner, profile_id="default", instance_id="owner", db=db)+ gates = {}++ def gate_in_turn_thread(live):+ # What TurnRunner binds for the agent thread: the frozen policy, the session key, its notifier.+ prompts = []++ def nobody_approves(data):+ prompts.append(data["pattern_key"])+ with A._lock:+ entry = A._gateway_queues[live.route][-1]+ entry.result = "deny"+ entry.event.set()++ vars_tokens = set_session_vars(platform="local", session_key=live.route, session_id=live.route)+ key_token = approval_context.set_current_session_key(live.route)+ policy_token = _ACTIVE_POLICY.set(policy_for_source(runner, live.source))+ A.register_gateway_notify(live.route, nobody_approves)+ try:+ return A.check_execute_code_guard("import shutil\nshutil.rmtree('victim')", "local")["approved"], prompts+ finally:+ A.unregister_gateway_notify(live.route)+ _ACTIVE_POLICY.reset(policy_token)+ approval_context.reset_current_session_key(key_token)+ clear_session_vars(vars_tokens)+ with A._lock:+ A._gateway_queues.pop(live.route, None)+ A._pending.pop(live.route, None)++ async def answer(event):+ gates[event.text] = await asyncio.to_thread(gate_in_turn_thread, authority.sessions[ref.session_id])+ return "ok"++ monkeypatch.setattr(runner, "_handle_message", answer)+ try:+ viewer = Principal("test-owner", "default", frozenset(+ {"session:create", "session:submit", "session:read", "session:approve"}), "viewer")+ ref = create_local_session(authority, viewer, dict(request_id="cli", source="cli", model="fixture",+ toolsets=[]))+ live = authority.sessions[ref.session_id]+ await authority.attach(viewer, ref)+ entry = runner.session_store.lookup_by_session_key(live.route)+ adapter = runner._adapter_for_source(live.source)++ await authority.submit(viewer, Submission("typed", ref, {"text": "typed by the viewer"}, "queue"))+ await async_wait_until(lambda: "typed by the viewer" in gates, timeout=10, what="the viewer's turn")+ assert await runner._admit_plugin_injection(+ adapter, live.source, session_key=live.route, session_id=entry.session_id,+ content="plugin injection", plugin_id="desk") is True+ await async_wait_until(lambda: "plugin injection" in gates, timeout=10, what="the injected turn")+ assert await admit_route_wake(runner, adapter, live.source, "loop tick", "loop-tick") is True+ await async_wait_until(lambda: "loop tick" in gates, timeout=10, what="the /loop tick")+ finally:+ db.close()++ assert gates == {"typed by the viewer": (True, []),+ "plugin injection": (False, ["execute_code"]),+ "loop tick": (False, ["execute_code"])}++[email protected]("request_id,payload,viewer", [+ ("typed", {"text": "hi", "cli_turn_v1": {"api_text": "[voice] hi"}, "finite": True}, True),+ ("typed", {"text": "hi", "local_operator_v1": {"principal_id": "op"}}, True),+ ('["plugin","desk","route","x"]', {"text": "hi", "local_automation_v1": {"identity": "x"}}, False),+ ('hosted:[{"task":1},0]', {"text": "room task"}, False),+ ("native", {"text": "hi", "native_text_v1": {"source": {}}}, False),+], ids=["cli-submit", "operator-submit", "automation", "hosted-room-task", "messaging"])+def test_viewer_input_is_only_a_session_submit_row(request_id, payload, viewer):+ from gateway.session_operator import is_viewer_input+ assert is_viewer_input({"request_id": request_id, "payload": payload}) is viewerdiff --git a/tests/tools/test_execute_code_local_session_approval.py b/tests/tools/test_execute_code_local_session_approval.pyindex fa64d4b8019..cc4ea95bacd 100644--- a/tests/tools/test_execute_code_local_session_approval.py+++ b/tests/tools/test_execute_code_local_session_approval.py@@ -33,6 +33,15 @@ def _policy(source: str, cwd: str) -> LocalSessionPolicy:toolsets=(), config_json="{}", request_json="{}", terminal_json="{}")+def _viewer_session():+ """The live session with its viewer attached, holding ``session:approve`` (what ``session.resume`` records)."""+ from types import SimpleNamespace+ from gateway.session_authority import LiveSession+ live = LiveSession(None, SESSION_KEY)+ live.subscribers["viewer"] = SimpleNamespace(capabilities=frozenset({"session:read", "session:approve"}))+ return live++@pytest.fixturedef turn(monkeypatch, tmp_path):"""Bind one gateway turn: the gateway's process-wide ask marker, manual mode, the session's@@ -51,7 +60,9 @@ def turn(monkeypatch, tmp_path):cleanups = []- def start(*, platform: str = "local", source: str | None = None, **set_answers):+ def start(*, platform: str = "local", source: str | None = None, viewer: bool = True, **set_answers):+ """``viewer``: the turn is one the session's viewer submitted (``execute_admission`` binds it);+ ``False`` is a plugin injection or another producer admission into the session."""monkeypatch.setenv("HERMES_EXEC_ASK", "1") # start_gateway() sets it process-widefor name in ("HERMES_INTERACTIVE", "HERMES_GATEWAY_SESSION", "HERMES_CRON_SESSION"):monkeypatch.delenv(name, raising=False)@@ -59,6 +70,10 @@ def turn(monkeypatch, tmp_path):vars_tokens = set_session_vars(platform=platform, session_key=SESSION_KEY, session_id=SESSION_KEY)key_token = approval_context.set_current_session_key(SESSION_KEY)policy_token = _ACTIVE_POLICY.set(_policy(source, str(tmp_path)) if source else None)+ if viewer:+ from gateway.session_ingress import viewer_turn+ viewer_token = viewer_turn.set(_viewer_session())+ cleanups.append(lambda: viewer_turn.reset(viewer_token))A.register_gateway_notify(SESSION_KEY, notify)cleanups.append(lambda: (A.unregister_gateway_notify(SESSION_KEY), _ACTIVE_POLICY.reset(policy_token),approval_context.reset_current_session_key(key_token),@@ -154,6 +169,21 @@ def _side_task(cwd):clear_session_vars(tokens)[email protected]("posix")+@LOCAL_SOURCES+def test_injected_turn_keeps_whole_script_gate(child_env, turn, source):+ """A plugin ``inject_message`` turn (or any other producer admission) into a local session is not+ one its viewer submitted: a script whose subprocess call no terminal() guard sees is approved as a+ whole, and with nobody approving it never runs."""+ victim = child_env / "victim"+ victim.mkdir()+ prompts = turn(source=source, viewer=False) # every prompt is denied+ _code, result = _run_unguarded_rm(victim)+ assert result.get("error") == _DENIED_SCRIPT, result+ assert "ran" not in result.get("output", "") and victim.is_dir()+ assert [p["pattern_key"] for p in prompts] == ["execute_code"]++@pytest.mark.platforms("posix")@pytest.mark.parametrize("source", ["cli", "acp"])@pytest.mark.parametrize("notifier", [True, False], ids=["during-parent-turn", "after-parent-turn"])diff --git a/tools/approval.py b/tools/approval.pyindex 5608fd959e6..d7dac191296 100644--- a/tools/approval.py+++ b/tools/approval.py@@ -1200,12 +1200,14 @@ _EXECUTE_CODE_DESCRIPTION = ()-def _is_local_foreground_turn() -> bool:- """A local session's own foreground turn: its frozen launch policy is local-interactive, it is not a- delegate_task child (sync or async; they inherit the parent's policy), and the turn's approval notifier is- registered under the bound session key (side tasks bind their own task key with none)."""+def _is_local_viewer_turn() -> bool:+ """A local session's turn its viewer submitted: its frozen launch policy is local-interactive, the admission+ is the viewer's own prompt (not a plugin injection or another producer admission), it is not a delegate_task+ child (sync or async; they inherit the parent's policy), and the turn's approval notifier is registered+ under the bound session key (side tasks bind their own task key with none)."""from agent.delegation_context import is_delegated_child_process_context- return (approval_context._is_local_interactive_session() and not is_delegated_child_process_context()+ return (approval_context._is_local_interactive_session() and approval_context.is_viewer_submitted_turn()+ and not is_delegated_child_process_context()and _gateway_notify_cb(get_current_session_key()) is not None)@@ -1254,9 +1256,10 @@ def check_execute_code_guard(code: str, env_type: str, has_host_access: bool = F# on every execute_code call. Ask-mode still takes this path even with INTERACTIVE set (how gateway/smart tests# and messaging ask-mode drive whole-script approval); when that leaks into a CLI with no notify callback, the# engine falls through to the CLI Dangerous Command panel instead of a silent pending_approval.- # A gateway-run local CLI/TUI/Desktop session keeps that interactive-CLI rule: the script's terminal() calls reach- # the session's own prompt per call, so no whole-script prompt (cron/-q resolved above; messaging/API unchanged).- if (not is_gateway and not is_ask) or _is_local_foreground_turn():+ # A gateway-run local CLI/TUI/Desktop session's own turns keep that interactive-CLI rule: the script's terminal()+ # calls reach the session's own prompt per call, so no whole-script prompt. Injected and automation turns keep the+ # gate (cron/-q resolved above; messaging/API unchanged).+ if (not is_gateway and not is_ask) or _is_local_viewer_turn():return _approved()session_key = get_current_session_key()diff --git a/tools/approval_context.py b/tools/approval_context.pyindex 46b52ff02e9..b5dc852217d 100644--- a/tools/approval_context.py+++ b/tools/approval_context.py@@ -96,6 +96,18 @@ def _is_local_interactive_session() -> bool:return policy is not None and policy.source in _LOCAL_INTERACTIVE_SOURCES+def is_viewer_submitted_turn() -> bool:+ """True while the executing turn is one its session's viewer submitted through ``session.submit``, as+ the gateway's FIFO drain recorded for this admission. A plugin ``inject_message`` turn, a delegation+ completion, a background-process or watch notice, a /loop tick, a heartbeat or a hosted-room task is+ not."""+ try:+ from gateway.session_ingress import viewer_turn+ except ImportError: # install without the gateway package: no admission is executing+ return False+ return viewer_turn.get() is not None++def set_current_session_key(session_key: str) -> contextvars.Token[str]:"""Bind the active approval session key to the current context."""return _approval_session_key.set(session_key or "")