Skip to content

The agent that grows with you

feat(approval): prepare GUI terminal asks before ordered execution

brooklyn!dd68d175674d
diff --git a/agent/terminal_approval_batch.py b/agent/terminal_approval_batch.py
new file mode 100644
index 00000000000..a4f49498ec4
--- /dev/null
+++ b/agent/terminal_approval_batch.py
@@ -0,0 +1,282 @@
+"""Prepare desktop terminal consent without running shells ahead of their turn.
+
+Workers keep execution middleware on its original stack. Only command approval
+runs ahead; the existing sequential executor releases each worker and persists
+its result before releasing the next. No terminal environment/cwd is acquired
+while preparing, and the real execution still runs every command guard.
+"""
+from __future__ import annotations
+
+import contextvars
+import copy
+import threading
+import time
+from contextlib import contextmanager
+from typing import Any
+
+from tools.thread_context import propagate_context_to_thread
+
+_batch: contextvars.ContextVar[Any] = contextvars.ContextVar("terminal_approval_batch", default=None)
+_slot: contextvars.ContextVar[Any] = contextvars.ContextVar("terminal_approval_slot", default=None)
+
+
+class _CancelledPreparation(Exception):
+ pass
+
+
+class _TerminalSlot:
+ def __init__(self, batch, parsed, index):
+ self.batch, self.parsed, self.index = batch, parsed, index
+ self.ready = threading.Event()
+ self.release = threading.Event()
+ self.future: Any = None
+ self.tids = []
+ self.preparing = False
+ self.args = None
+ self.decision = None
+ self.guard_key = None
+ self.claimed = False
+
+ def check_cancelled(self):
+ if self.batch.cancelled.is_set() or self.batch.agent._interrupt_requested:
+ raise _CancelledPreparation("Terminal approval preparation cancelled; command was not started")
+
+ def prepare(self, ref):
+ from tools import terminal_tool as tt
+ self.check_cancelled()
+ self.args = copy.deepcopy(ref.args)
+ self.preparing = True
+ try:
+ # Read policy only. _plan_execution/_acquire_env resolve cwd and
+ # shell state later, after the previous result has been persisted.
+ config = tt._get_env_config()
+ if isinstance(ref.args.get("command"), str):
+ from tools.approval_context import set_current_observability_context, reset_current_observability_context
+ tokens = set_current_observability_context(
+ tool_call_id=ref.call_id, session_id=self.batch.agent.session_id or "",
+ turn_id=getattr(self.batch.agent, "_current_turn_id", "") or "",
+ )
+ try:
+ self.guard_key = (ref.args["command"], config["env_type"], tt._docker_has_host_access(config))
+ self.decision = tt._check_all_guards(*self.guard_key)
+ finally:
+ reset_current_observability_context(tokens)
+ finally:
+ self.preparing = False
+ self.ready.set()
+ while not self.release.wait(0.1):
+ self.check_cancelled()
+ self.check_cancelled()
+
+ def run(self):
+ from agent import tool_executor as te
+ token = _slot.set(self)
+ pc, batch = self.parsed, self.batch
+ ref = pc.ref(batch.task_id)
+ try:
+ with te._registered_tool_worker(batch.agent) as tid:
+ self.tids.append(tid)
+ self.check_cancelled()
+ dispatch = te._resolve_sequential_dispatch(batch.agent, ref, batch.messages)
+ return te._run_agent_tool_execution_middleware(
+ batch.agent, **ref.middleware_kwargs(), execute=dispatch.execute,
+ scope_block=pc.scope_block, display_index=self.index + 1,
+ authorization_gate=batch.authorization_gate,
+ )
+ finally:
+ self.ready.set()
+ _slot.reset(token)
+
+
+class _TerminalBatch:
+ def __init__(self, agent, messages, task_id, parsed):
+ from agent.tool_executor import _ConcurrentToolAuthorizationGate
+ from tools.daemon_pool import DaemonThreadPoolExecutor
+ self.agent, self.messages, self.task_id = agent, messages, task_id
+ self.cancelled = threading.Event()
+ self.pending_approvals = [] # guarded by tools.approval._lock
+ self.authorization_gate = _ConcurrentToolAuthorizationGate()
+ self.executor = DaemonThreadPoolExecutor(max_workers=len(parsed))
+ self.slots = [_TerminalSlot(self, pc, i) for i, pc in enumerate(parsed)]
+
+ def start(self):
+ from agent.tool_executor import _resolve_sequential_tool_timeout
+ for slot in self.slots:
+ slot.check_cancelled()
+ slot.future = self.executor.submit(propagate_context_to_thread(slot.run))
+ timeout = _resolve_sequential_tool_timeout()
+ started = time.monotonic()
+ baseline = self.authorization_gate.excluded_seconds()
+ # Proceed once the worker publishes a human request OR completes
+ # preparation. A wedged plugin must not hold the batch forever.
+ while not slot.ready.wait(0.1):
+ slot.check_cancelled()
+ elapsed = time.monotonic() - started - (self.authorization_gate.excluded_seconds() - baseline)
+ if timeout is not None and elapsed >= timeout:
+ raise TimeoutError("Terminal approval preparation timed out; commands were not started")
+
+ def close(self):
+ from agent.tool_executor import _interrupt_worker_tids
+ from tools import approval
+ # Withdraw only this batch's requests, including a worker wedged in
+ # notify_cb. Thread interrupts alone leave those requests actionable.
+ with approval._lock:
+ self.cancelled.set()
+ for session_key, entry in self.pending_approvals:
+ queue = approval._gateway_queues.get(session_key, [])
+ if entry in queue:
+ queue.remove(entry)
+ entry.result = "deny"
+ entry.event.set()
+ if not queue:
+ approval._gateway_queues.pop(session_key, None)
+ self.pending_approvals.clear()
+ for slot in self.slots:
+ slot.release.set()
+ if slot.future is not None and not slot.future.done():
+ _interrupt_worker_tids(self.agent, slot.tids)
+ slot.future.cancel()
+ self.executor.shutdown(wait=False, cancel_futures=True)
+
+
+def prepare_current_terminal(ref):
+ slot = _slot.get()
+ if slot is not None and ref.name == "terminal":
+ slot.prepare(ref)
+
+
+def bind_prepared_dispatch(dispatch):
+ """A middleware-owned thread must not lose the batch's execution barrier."""
+ slot = _slot.get()
+ if slot is None:
+ return dispatch
+ from agent.tool_executor import _registered_tool_worker
+
+ owner_tid = threading.get_ident()
+
+ def tracked(*args, **kwargs):
+ if threading.get_ident() == owner_tid:
+ return dispatch(*args, **kwargs)
+ with _registered_tool_worker(slot.batch.agent) as tid:
+ slot.tids.append(tid)
+ slot.check_cancelled()
+ return dispatch(*args, **kwargs)
+
+ invoke = propagate_context_to_thread(tracked)
+ # Each batch slot has exactly one dispatch. Reject concurrent/replayed
+ # continuations before entering its captured Context on another thread.
+ lock = threading.Lock()
+ claimed = False
+
+ def once(*args, **kwargs):
+ nonlocal claimed
+ with lock:
+ if claimed:
+ raise RuntimeError("Hermes tool execution callback invoked more than once")
+ claimed = True
+ return invoke(*args, **kwargs)
+
+ return once
+
+
+def take_prepared_call(call_id):
+ batch = _batch.get()
+ if batch is None:
+ return None
+ for slot in batch.slots:
+ if slot.parsed.ref(batch.task_id).call_id == call_id and not slot.claimed:
+ slot.claimed = True
+ slot.check_cancelled()
+ slot.release.set()
+ return slot
+ return None
+
+
+def approval_published():
+ slot = _slot.get()
+ if slot is not None:
+ slot.ready.set()
+
+
+def register_prepared_approval(session_key, entry):
+ """Called under the approval queue lock, before enqueueing the request."""
+ slot = _slot.get()
+ if slot is not None:
+ slot.check_cancelled()
+ slot.batch.pending_approvals.append((session_key, entry))
+
+
+def consume_prepared_guard(command, env_type, has_host_access):
+ slot = _slot.get()
+ if slot is None or slot.preparing:
+ return None
+ slot.check_cancelled()
+ from tools.approval_context import _approval_tool_call_id
+ if (_approval_tool_call_id.get() != slot.parsed.ref(slot.batch.task_id).call_id
+ or slot.guard_key != (command, env_type, has_host_access)):
+ return None
+ decision, slot.decision = slot.decision, None # single-use, even for identical calls
+ return decision
+
+
+def preparing_terminal_approval():
+ slot = _slot.get()
+ return slot is not None and slot.preparing
+
+
+def validate_prepared_terminal(args):
+ slot = _slot.get()
+ if slot is not None:
+ slot.check_cancelled()
+ # Middleware/registry coercion must not turn a prepared consent into
+ # authority for different arguments, even with identical display text.
+ if args != slot.args:
+ slot.decision = None
+ raise RuntimeError("Terminal arguments changed after approval preparation; command was not started")
+
+
+def terminal_approval_runs(agent, calls):
+ """Keep nonterminal barriers, but batch adjacent terminals in mixed segments."""
+ from itertools import groupby
+ from agent.tool_executor import _parse_tool_call
+
+ def is_terminal(call):
+ pc = _parse_tool_call(agent, call, flatten_probe=True)
+ return pc.name == "terminal" and pc.parse_error is None
+
+ for _, run in groupby(calls, key=is_terminal):
+ yield list(run)
+
+
+@contextmanager
+def terminal_approval_batch(agent, calls, messages, task_id):
+ from gateway.session_context import get_session_env
+ from tools import approval
+ from agent.tool_executor import _parse_tool_call
+ if (len(calls) < 2 or get_session_env("HERMES_SESSION_SOURCE") != "gui"
+ or approval._gateway_notify_cb(approval.get_current_session_key()) is None):
+ yield
+ return
+ parsed = [_parse_tool_call(agent, call, flatten_probe=True) for call in calls]
+ # Never prepare across a nonterminal barrier; leave mixed segments and
+ # malformed calls with the established sequential path.
+ ids = [pc.ref(task_id).call_id for pc in parsed]
+ if (any(pc.name != "terminal" or pc.parse_error is not None for pc in parsed)
+ or not all(ids) or len(set(ids)) != len(ids)):
+ yield
+ return
+ batch = _TerminalBatch(agent, messages, task_id, parsed)
+ token = _batch.set(batch)
+ try:
+ if not agent._interrupt_requested and not getattr(agent, "_incremental_persistence_failed", False):
+ try:
+ batch.start()
+ except (_CancelledPreparation, TimeoutError) as exc:
+ batch.close()
+ agent.interrupt(str(exc))
+ # The sequential path must still persist a result for every
+ # assistant tool call, even if preparation never finished.
+ yield
+ finally:
+ batch.close()
+ _batch.reset(token)
diff --git a/agent/tool_executor.py b/agent/tool_executor.py
index b48478db679..dde39df095b 100644
--- a/agent/tool_executor.py
+++ b/agent/tool_executor.py
@@ -690,6 +690,8 @@ def _dispatch_authorized_once(
elif ref.name == "skill_manage":
agent._iters_since_skill = 0
+ from agent.terminal_approval_batch import prepare_current_terminal
+ prepare_current_terminal(ref)
_advance_start_order(lambda: _begin_tool_execution(agent, ref, display_index))
return _run_with_activity_heartbeat(agent, ref.name, lambda: execute(ref.args))
@@ -737,6 +739,9 @@ def _run_agent_tool_execution_middleware(
authorization_gate=authorization_gate,
)
+ from agent.terminal_approval_batch import bind_prepared_dispatch
+ _authorized_dispatch = bind_prepared_dispatch(_authorized_dispatch)
+
def _hermes_pipeline(relay_args: dict[str, Any]) -> Any:
request_result = apply_tool_request_middleware(
function_name,
@@ -845,13 +850,23 @@ def _run_sequential_tool_execution_middleware(
timeout_s = None if function_name in _SEQUENTIAL_DEADLINE_EXEMPT_TOOLS else _resolve_sequential_tool_timeout()
ref = _ToolCallRef(function_name, function_args, effective_task_id, tool_call_id, middleware_trace)
kwargs = dict(ref.middleware_kwargs(), execute=execute, scope_block=scope_block, display_index=display_index)
+ from agent.terminal_approval_batch import take_prepared_call
+ prepared = take_prepared_call(tool_call_id)
+ if prepared is not None:
+ authorization_gate = prepared.batch.authorization_gate
+ executor = prepared.batch.executor
+ worker_tid = prepared.tids
+ future = prepared.future
+ else:
+ authorization_gate = None
if function_name in _NEVER_PARALLEL_TOOLS:
return _run_agent_tool_execution_middleware(agent, **kwargs)
from tools.daemon_pool import DaemonThreadPoolExecutor
- authorization_gate = _ConcurrentToolAuthorizationGate()
- worker_tid: list[int] = []
+ if prepared is None:
+ authorization_gate = _ConcurrentToolAuthorizationGate()
+ worker_tid: list[int] = []
def _run() -> _ManagedToolResult:
with _registered_tool_worker(agent) as tid:
@@ -860,8 +875,9 @@ def _run_sequential_tool_execution_middleware(
if ref.trace is None:
ref.trace = []
- executor = DaemonThreadPoolExecutor(max_workers=1)
- future = executor.submit(propagate_context_to_thread(_run))
+ if prepared is None:
+ executor = DaemonThreadPoolExecutor(max_workers=1)
+ future = executor.submit(propagate_context_to_thread(_run))
deadline = time.monotonic() + timeout_s if timeout_s is not None else None
started = time.monotonic()
abandoned = False
@@ -894,13 +910,19 @@ def _run_sequential_tool_execution_middleware(
duration_ms=int(timeout_s * 1000), status="timeout", error_type="tool_timeout", error_message=message,
)
abandoned = True
+ if prepared is not None:
+ # A timed-out shell may still be unwinding. Never release a later
+ # prepared command into overlapping execution.
+ prepared.batch.close()
+ agent.interrupt("terminal batch tool did not complete")
future.cancel()
if state == "timeout":
_interrupt_worker_tids(agent, worker_tid)
return _abandoned_sequential_result(agent, ref, message, result_cls, **outcome)
finally:
# Never join a wedged worker (daemon pool also keeps it out of the atexit join).
- executor.shutdown(wait=not abandoned, cancel_futures=abandoned)
+ if prepared is None:
+ executor.shutdown(wait=not abandoned, cancel_futures=abandoned)
def _safe_callback(callback, label: str, *args, **kwargs) -> None:
@@ -1672,6 +1694,18 @@ def _publish_sequential_result(agent, messages: list, ref: _ToolCallRef, managed
def execute_tool_calls_sequential(agent, assistant_message, messages: list, effective_task_id: str, api_call_count: int = 0, *, finalize: bool = True) -> None:
+ from types import SimpleNamespace
+ from agent.terminal_approval_batch import terminal_approval_batch, terminal_approval_runs
+ for calls in terminal_approval_runs(agent, assistant_message.tool_calls):
+ with terminal_approval_batch(agent, calls, messages, effective_task_id):
+ _execute_tool_calls_sequential(agent, SimpleNamespace(tool_calls=calls), messages, effective_task_id, api_call_count, finalize=False)
+ if getattr(agent, "_incremental_persistence_failed", False):
+ return
+ if finalize:
+ _finalize_tool_batch(agent, messages, effective_task_id, len(assistant_message.tool_calls), _budget_for_agent(agent))
+
+
+def _execute_tool_calls_sequential(agent, assistant_message, messages: list, effective_task_id: str, api_call_count: int = 0, *, finalize: bool = True) -> None:
"""Execute tool calls sequentially (single calls or interactive tools). ``finalize=False``
skips end-of-batch budget enforcement and /steer injection (the segmented dispatcher
owns turn-end work)."""
diff --git a/tests/agent/test_terminal_approval_batch.py b/tests/agent/test_terminal_approval_batch.py
new file mode 100644
index 00000000000..31069dcba33
--- /dev/null
+++ b/tests/agent/test_terminal_approval_batch.py
@@ -0,0 +1,221 @@
+"""Desktop batches publish consent together, never shell effects together."""
+
+import json
+import queue
+import threading
+from types import SimpleNamespace
+from unittest.mock import patch
+
+import pytest
+
+from run_agent import AIAgent
+from gateway.session_context import set_session_vars, clear_session_vars
+from tools import approval
+from tools.thread_context import propagate_context_to_thread
+
+
+def _call(call_id, command):
+ return SimpleNamespace(id=call_id, type="function", function=SimpleNamespace(
+ name="terminal", arguments=json.dumps({"command": command})))
+
+
+def _agent():
+ from tools.terminal_tool import TERMINAL_SCHEMA
+ from tools.file_tools import READ_FILE_SCHEMA
+ with (
+ patch("model_tools.get_tool_definitions", return_value=[
+ {"type": "function", "function": schema}
+ for schema in (TERMINAL_SCHEMA, READ_FILE_SCHEMA)
+ ]),
+ patch("model_tools.check_toolset_requirements", return_value={}),
+ patch("agent.process_bootstrap.OpenAI"),
+ patch("agent.model_metadata.fetch_model_metadata", return_value={}),
+ ):
+ return AIAgent(api_key="test-key", base_url="https://openrouter.ai/api/v1",
+ quiet_mode=True, skip_context_files=True, skip_memory=True, platform="gui")
+
+
[email protected]("read_count", [0, 1, 2])
[email protected]("threaded_middleware", [False, True])
+def test_desktop_publishes_final_commands_before_wait_and_runs_in_order(tmp_path, monkeypatch, read_count, threaded_middleware):
+ from tools.terminal_scope import terminal_scope
+ from tools.terminal_tool_lifecycle import cleanup_vm
+ monkeypatch.delenv("HERMES_DESKTOP", raising=False)
+ monkeypatch.setenv("HERMES_EXEC_ASK", "1")
+ monkeypatch.setenv("TERMINAL_ENV", "local")
+ monkeypatch.setenv("TERMINAL_CWD", str(tmp_path))
+ monkeypatch.setattr("tools.approval_context._get_approval_mode", lambda: "manual")
+ monkeypatch.setattr("tools.approval._tirith_scan", lambda command: {"action": "allow"})
+ monkeypatch.setattr("agent.title_generator.maybe_auto_title", lambda *a, **kw: None)
+ nested = tmp_path / "nested"
+ nested.mkdir()
+ key = "desktop-terminal-batch"
+ agent = _agent()
+ published = queue.Queue()
+ approval.register_gateway_notify(key, published.put)
+ tokens = set_session_vars(source="gui", session_key=key, cwd=str(tmp_path), cron_session="")
+ calls = [_call("first", "original-first"), _call("second", "original-second")]
+ if read_count:
+ source = tmp_path / "input.txt"
+ source.write_text("input")
+ calls[:0] = [SimpleNamespace(id=f"read-{i}", type="function", function=SimpleNamespace(
+ name="read_file", arguments=json.dumps({"path": str(source)}))) for i in range(read_count)]
+ commands = {"original-first": f"rm -rf absent-first; cd '{nested}'", "original-second": "rm -rf absent-second; pwd"}
+ policy = []
+ executed = []
+ flushed = []
+ messages = []
+ errors = []
+ replay_errors = []
+
+ if threaded_middleware:
+ def middleware(name, args, execute, **kwargs):
+ if name != "terminal":
+ return execute(args)
+ results = []
+ def dispatch():
+ results.append(execute(args))
+ try:
+ execute(args)
+ except RuntimeError as exc:
+ replay_errors.append(str(exc))
+ # Middleware may move its continuation onto a fresh thread.
+ thread = threading.Thread(target=dispatch, daemon=True)
+ thread.start()
+ thread.join(20)
+ return results[0]
+ monkeypatch.setattr("hermes_cli.middleware.run_tool_execution_middleware", middleware)
+
+ def pre_hook(name, args, **kwargs):
+ if name != "terminal":
+ return None, args
+ policy.append(args["command"])
+ return None, {**args, "command": commands[args["command"]]}
+
+ def started(call_id, name, args):
+ if name != "terminal":
+ return
+ executed.append((call_id, args["command"], list(flushed)))
+
+ agent.tool_start_callback = started
+ agent._flush_messages_to_session_db = lambda rows, **kw: flushed.append([r["tool_call_id"] for r in rows]) or True
+
+ def run():
+ try:
+ agent._execute_tool_calls(SimpleNamespace(tool_calls=calls), messages, key)
+ except BaseException as exc:
+ errors.append(exc)
+
+ with terminal_scope({"TERMINAL_ENV": "local", "TERMINAL_CWD": str(tmp_path)}), patch(
+ "hermes_cli.plugins._dispatch_pre_tool_call_hooks", side_effect=pre_hook
+ ):
+ worker = threading.Thread(target=propagate_context_to_thread(run), daemon=True)
+ worker.start()
+ try:
+ first = published.get(timeout=10)
+ second = published.get(timeout=5)
+ assert [first["command"], second["command"]] == list(commands.values())
+ assert policy == list(commands)
+ assert executed == []
+ assert approval.ack_gateway_approval(key, second["request_id"])
+ assert executed == []
+ assert approval.resolve_gateway_approval(key, "once", request_id=second["request_id"]) == 1
+ assert executed == []
+ assert approval.resolve_gateway_approval(key, "once", request_id=first["request_id"]) == 1
+ worker.join(timeout=15)
+ assert not worker.is_alive()
+ assert errors == []
+ assert [item[:2] for item in executed] == [("first", commands["original-first"]), ("second", commands["original-second"])]
+ assert len(replay_errors) == (2 if threaded_middleware else 0)
+ assert executed[1][2][-1] == [c.id for c in calls[:-1]]
+ assert "first" not in {call_id for flush in executed[0][2] for call_id in flush}
+ assert [m["tool_call_id"] for m in messages] == [c.id for c in calls]
+ assert str(nested) in json.loads(messages[-1]["content"])["output"]
+ assert approval.list_gateway_approvals(key) == []
+ finally:
+ agent.interrupt("test cleanup")
+ approval.unregister_gateway_notify(key)
+ worker.join(timeout=5)
+ cleanup_vm(key)
+ clear_session_vars(tokens)
+
+
+def test_cancelled_preparation_drains_requests_without_reusing_once(tmp_path, monkeypatch):
+ from tools.terminal_scope import terminal_scope
+ from tools.terminal_tool_lifecycle import cleanup_vm
+
+ monkeypatch.setenv("HERMES_EXEC_ASK", "1")
+ monkeypatch.setattr("tools.approval_context._get_approval_mode", lambda: "manual")
+ monkeypatch.setattr("tools.approval._tirith_scan", lambda command: {"action": "allow"})
+ monkeypatch.setattr("agent.title_generator.maybe_auto_title", lambda *a, **kw: None)
+ key = "cancelled-terminal-batch"
+ command = "rm -rf absent; printf executed > effect.txt"
+ published = queue.Queue()
+ release_notify = threading.Event()
+ messages, errors = [], []
+ agent = _agent()
+ agent._flush_messages_to_session_db = lambda *a, **kw: True
+ calls = [_call(call_id, command) for call_id in ("first", "second", "third")]
+ notices = []
+
+ def notify(data):
+ notices.append(data)
+ published.put(data)
+ if len(notices) == 3:
+ release_notify.wait(10)
+
+ def run(target, batch_calls, rows):
+ try:
+ target._execute_tool_calls(SimpleNamespace(tool_calls=batch_calls), rows, key)
+ except BaseException as exc:
+ errors.append(exc)
+
+ approval.register_gateway_notify(key, notify)
+ tokens = set_session_vars(source="gui", session_key=key, cwd=str(tmp_path), cron_session="")
+ with terminal_scope({"TERMINAL_ENV": "local", "TERMINAL_CWD": str(tmp_path)}):
+ worker = threading.Thread(target=propagate_context_to_thread(lambda: run(agent, calls, messages)), daemon=True)
+ retry_worker = None
+ retry_agent = None
+ worker.start()
+ try:
+ requests = [published.get(timeout=10) for _ in calls]
+ assert len({r["request_id"] for r in requests}) == len(calls)
+ assert approval.resolve_gateway_approval(key, "once", request_id=requests[1]["request_id"]) == 1
+ agent.interrupt("cancel while publishing")
+ worker.join(5)
+ assert not worker.is_alive()
+ assert errors == []
+ assert [row["tool_call_id"] for row in messages] == [c.id for c in calls]
+ assert approval.list_gateway_approvals(key) == []
+ assert not (tmp_path / "effect.txt").exists()
+ assert approval.resolve_gateway_approval(key, "once", request_id=requests[0]["request_id"]) == 0
+ release_notify.set()
+
+ # Same command AND call id in a later run still needs fresh consent.
+ retry_agent = _agent()
+ retry_agent._flush_messages_to_session_db = lambda *a, **kw: True
+ retry_rows = []
+ retry_worker = threading.Thread(target=propagate_context_to_thread(
+ lambda: run(retry_agent, [_call("second", command)], retry_rows)), daemon=True)
+ retry_worker.start()
+ request = published.get(timeout=10)
+ assert request["request_id"] not in {r["request_id"] for r in requests}
+ assert not (tmp_path / "effect.txt").exists()
+ assert approval.resolve_gateway_approval(key, "deny", request_id=request["request_id"]) == 1
+ retry_worker.join(5)
+ assert not retry_worker.is_alive()
+ assert errors == []
+ assert json.loads(retry_rows[0]["content"])["status"] == "blocked"
+ assert not (tmp_path / "effect.txt").exists()
+ assert approval.list_gateway_approvals(key) == []
+ finally:
+ release_notify.set()
+ agent.interrupt("test cleanup")
+ if retry_agent is not None:
+ retry_agent.interrupt("test cleanup")
+ approval.unregister_gateway_notify(key)
+ worker.join(5)
+ if retry_worker is not None:
+ retry_worker.join(5)
+ cleanup_vm(key)
+ clear_session_vars(tokens)
diff --git a/tools/approval.py b/tools/approval.py
index 1f95f65685f..062cd78c035 100644
--- a/tools/approval.py
+++ b/tools/approval.py
@@ -1137,6 +1137,11 @@ def check_all_command_guards(command: str, env_type: str,
if blocked is not None:
return blocked
+ from agent.terminal_approval_batch import consume_prepared_guard
+ prepared = consume_prepared_guard(command, env_type, has_host_access)
+ if prepared is not None:
+ return prepared
+
approval_mode = approval_context._get_approval_mode()
if _yolo_active() or approval_mode == "off":
return _approved()
diff --git a/tools/approval_gateway_wait.py b/tools/approval_gateway_wait.py
index 5a3f8f2cb01..f433713229e 100644
--- a/tools/approval_gateway_wait.py
+++ b/tools/approval_gateway_wait.py
@@ -141,6 +141,7 @@ def _await_gateway_decision(session_key: str, notify_cb, approval_data: dict, *,
the leader's ``session``/``always``/``deny``/timeout; a ``once`` covers only
the leader, so the follower falls through to a fresh prompt."""
from tools import approval as _approval
+ from agent.terminal_approval_batch import approval_published, preparing_terminal_approval, register_prepared_approval
primary_key = approval_data.get("pattern_key", "")
payload = {
@@ -155,13 +156,14 @@ def _await_gateway_decision(session_key: str, notify_cb, approval_data: dict, *,
leader = next((e for e in _approval._gateway_queues.get(session_key, [])
if e.data.get("command") == approval_data.get("command")
and list(e.data.get("pattern_keys") or []) == keys), None)
- if leader is not None:
+ if leader is not None and not preparing_terminal_approval():
adopted = _await_coalesced_leader(session_key, leader, payload)
if adopted is not None:
return adopted
entry = _ApprovalEntry(approval_data)
with _approval._lock:
+ register_prepared_approval(session_key, entry)
_approval._gateway_queues.setdefault(session_key, []).append(entry)
def _drop_entry(reason: str) -> None:
@@ -183,6 +185,7 @@ def _await_gateway_decision(session_key: str, notify_cb, approval_data: dict, *,
# Bridges sync agent thread → async gateway.
try:
notify_cb(dict(entry.data))
+ approval_published()
except Exception as exc:
logger.warning("Gateway approval notify failed: %s", exc)
_drop_entry("notify_failed")
diff --git a/tools/terminal_tool.py b/tools/terminal_tool.py
index 6935bbd88bd..3ab015c4f38 100644
--- a/tools/terminal_tool.py
+++ b/tools/terminal_tool.py
@@ -1353,6 +1353,8 @@ TERMINAL_SCHEMA = {
def _handle_terminal(args, **kw):
+ from agent.terminal_approval_batch import validate_prepared_terminal
+ validate_prepared_terminal(args)
# Models sometimes send execute_code's ``code`` here; name the stray
# argument and the right tool instead of failing on command=None.
if "command" not in args and "code" in args: