The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(approval): skip the execute_code gate only while an approving viewer is attached
unsupportedpastels4e0806d5dcff
diff --git a/gateway/session_ingress.py b/gateway/session_ingress.pyindex ffe8c6b29b1..6a35f30fdb6 100644--- a/gateway/session_ingress.py+++ b/gateway/session_ingress.py@@ -14,7 +14,7 @@ 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)+viewer_turn: ContextVar = 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.diff --git a/tests/gateway/test_local_turn_origin_execute_code_gate.py b/tests/gateway/test_local_turn_origin_execute_code_gate.pyindex 7bee8e11a6b..27eb03dba17 100644--- a/tests/gateway/test_local_turn_origin_execute_code_gate.py+++ b/tests/gateway/test_local_turn_origin_execute_code_gate.py@@ -76,7 +76,7 @@ async def test_only_the_viewers_own_turn_skips_the_whole_script_gate(tmp_path, mref = 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)+ subscription = (await authority.attach(viewer, ref)).subscription_identry = runner.session_store.lookup_by_session_key(live.route)adapter = runner._adapter_for_source(live.source)@@ -88,12 +88,17 @@ async def test_only_the_viewers_own_turn_skips_the_whole_script_gate(tmp_path, mawait 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 Trueawait async_wait_until(lambda: "loop tick" in gates, timeout=10, what="the /loop tick")+ # The viewer detaches: its queued turn still runs, with nobody attached who can answer.+ await authority.detach(viewer, subscription)+ await authority.submit(viewer, Submission("queued", ref, {"text": "typed, then detached"}, "queue"))+ await async_wait_until(lambda: "typed, then detached" in gates, timeout=10, what="the detached turn")finally:db.close()assert gates == {"typed by the viewer": (True, []),"plugin injection": (False, ["execute_code"]),- "loop tick": (False, ["execute_code"])}+ "loop tick": (False, ["execute_code"]),+ "typed, then detached": (False, ["execute_code"])}@pytest.mark.parametrize("request_id,payload,viewer", [diff --git a/tests/tools/test_execute_code_local_session_approval.py b/tests/tools/test_execute_code_local_session_approval.pyindex cc4ea95bacd..2cc2cd0702f 100644--- a/tests/tools/test_execute_code_local_session_approval.py+++ b/tests/tools/test_execute_code_local_session_approval.py@@ -33,12 +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)."""+def _viewer_session(attached: str = "approver"):+ """The live session; ``attached`` is who ``session.resume`` recorded as subscribed: a viewer holding+ ``session:approve``, a read-only one, or nobody."""from types import SimpleNamespacefrom gateway.session_authority import LiveSessionlive = LiveSession(None, SESSION_KEY)- live.subscribers["viewer"] = SimpleNamespace(capabilities=frozenset({"session:read", "session:approve"}))+ capabilities = {"approver": {"session:read", "session:approve"}, "read-only": {"session:read"}}.get(attached)+ if capabilities is not None:+ live.subscribers["viewer"] = SimpleNamespace(capabilities=frozenset(capabilities))return live@@ -60,9 +63,11 @@ def turn(monkeypatch, tmp_path):cleanups = []- def start(*, platform: str = "local", source: str | None = None, viewer: bool = True, **set_answers):+ def start(*, platform: str = "local", source: str | None = None, viewer: bool = True,+ attached: str = "approver", **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."""+ ``False`` is a plugin injection or another producer admission into the session. ``attached``: see+ ``_viewer_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)@@ -72,7 +77,7 @@ def turn(monkeypatch, tmp_path):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())+ viewer_token = viewer_turn.set(_viewer_session(attached))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),@@ -184,6 +189,22 @@ def test_injected_turn_keeps_whole_script_gate(child_env, turn, source):assert [p["pattern_key"] for p in prompts] == ["execute_code"][email protected]("posix")[email protected]("source", ["cli", "gui"])[email protected]("attached", ["nobody", "read-only"])+def test_viewer_turn_with_no_approver_attached_keeps_whole_script_gate(child_env, turn, source, attached):+ """The turn's notifier is registered for every session turn, viewer attached or not; the exemption also+ needs an attached viewer that can answer approvals. Otherwise the script is approved as a whole and,+ with nobody approving, never runs."""+ victim = child_env / "victim"+ victim.mkdir()+ prompts = turn(source=source, attached=attached) # 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 d7dac191296..23d6467c7aa 100644--- a/tools/approval.py+++ b/tools/approval.py@@ -1201,12 +1201,14 @@ _EXECUTE_CODE_DESCRIPTION = (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)."""+ """A local session's turn its viewer submitted, with that viewer there to answer: its frozen launch policy is+ local-interactive, the admission is the viewer's own prompt (not a plugin injection or another producer+ admission) and a viewer holding ``session:approve`` is attached now, 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. The notifier is registered for every session turn, so it only tells side tasks (their own task+ key, none registered) apart; it does not show anyone is attached."""from agent.delegation_context import is_delegated_child_process_context- return (approval_context._is_local_interactive_session() and approval_context.is_viewer_submitted_turn()+ return (approval_context._is_local_interactive_session() and approval_context.is_viewer_turn_with_approver()and not is_delegated_child_process_context()and _gateway_notify_cb(get_current_session_key()) is not None)diff --git a/tools/approval_context.py b/tools/approval_context.pyindex b5dc852217d..90e48de728b 100644--- a/tools/approval_context.py+++ b/tools/approval_context.py@@ -96,16 +96,21 @@ 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."""+def is_viewer_turn_with_approver() -> 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) and a viewer that can answer approvals is attached now:+ a subscriber holding ``session:approve``, the only answer the gateway's approval resolver accepts. 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 never a viewer turn."""try:from gateway.session_ingress import viewer_turnexcept ImportError: # install without the gateway package: no admission is executingreturn False- return viewer_turn.get() is not None+ live = viewer_turn.get()+ if live is None:+ return False+ with live.event_stream.lock:+ return any("session:approve" in member.capabilities for member in live.subscribers.values())def set_current_session_key(session_key: str) -> contextvars.Token[str]: