The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(approval): a turn can hold its approval prompts open until answered
Brooklyn Nicholsone57fa350cbf2
diff --git a/tests/tools/test_approval_prompts_wait_for_answer.py b/tests/tools/test_approval_prompts_wait_for_answer.pynew file mode 100644index 00000000000..549cb720fa6--- /dev/null+++ b/tests/tools/test_approval_prompts_wait_for_answer.py@@ -0,0 +1,80 @@+"""CLI / TUI / Desktop turns hold approval prompts open until answered; ``approvals.timeout`` is the+messaging-platform deadline only.++A surface that binds ``set_prompts_wait_for_answer()`` around its turn must get (1) an approval wait that+outlives ``approvals.timeout`` and (2) human-wait accounting that keeps excluding that wait from the batch+deadline even when the deadline loop reads it from a context that never saw the binding.+"""++import contextvars+import threading+import time++from tools import approval as mod+from tools import approval_context as ctx+from tools import approval_gateway_wait as wait_mod+from tools import approval_human_wait as human_wait+++APPROVAL = {"command": "rm -rf build", "description": "d", "pattern_key": "dangerous", "pattern_keys": ["dangerous"]}+++def _bound(fn):+ """Run *fn* in a fresh context that has the CLI/TUI/Desktop binding, like a surface turn."""+ def run():+ ctx.set_prompts_wait_for_answer()+ return fn()+ return lambda: contextvars.Context().run(run)+++def _decide_in_thread(session_key, *, attended):+ box = {}+ wait = lambda: box.__setitem__( # noqa: E731+ "decision", wait_mod._await_gateway_decision(session_key, lambda data: None, dict(APPROVAL)))+ thread = threading.Thread(target=_bound(wait) if attended else wait, daemon=True)+ thread.start()+ return thread, box+++def test_attended_approval_outlives_approvals_timeout_and_messaging_still_times_out(monkeypatch):+ mod._gateway_queues.clear()+ monkeypatch.setattr(ctx, "_get_approval_config", lambda: {"timeout": 1})+ monkeypatch.setattr(ctx, "_fire_approval_hook", lambda name, **kw: None)++ attended, attended_box = _decide_in_thread("attended-session", attended=True)+ messaging, messaging_box = _decide_in_thread("messaging-session", attended=False)++ messaging.join(timeout=5)+ assert messaging_box["decision"] == {"resolved": False, "choice": None, "reason": None}++ attended.join(timeout=1.5) # well past approvals.timeout+ assert attended.is_alive()+ assert mod.resolve_gateway_approval("attended-session", "once") == 1+ attended.join(timeout=5)+ assert attended_box["decision"] == {"resolved": True, "choice": "once", "reason": None}+++def test_attended_wait_stays_excluded_when_read_from_an_unbound_context(monkeypatch):+ """The batch deadline loop may poll ``human_wait_seconds`` from a context without the binding; an open+ attended window must still count in full there, while a messaging window stays clamped."""+ monkeypatch.setattr(ctx, "_get_approval_config", lambda: {"timeout": 0})+ monkeypatch.setattr(human_wait, "HUMAN_WAIT_MARGIN_S", 0.0)+ release = threading.Event()++ def hold(session_key):+ with human_wait.human_wait_window(session_key):+ release.wait(5)++ threads = [threading.Thread(target=_bound(lambda: hold("attended-window")), daemon=True),+ threading.Thread(target=lambda: hold("messaging-window"), daemon=True)]+ for thread in threads:+ thread.start()+ try:+ time.sleep(0.3)+ assert human_wait.human_wait_seconds("attended-window") >= 0.25+ assert human_wait.human_wait_seconds("messaging-window") == 0.0+ finally:+ release.set()+ for thread in threads:+ thread.join(timeout=5)+ assert human_wait.human_wait_seconds("attended-window") >= 0.25diff --git a/tools/approval_context.py b/tools/approval_context.pyindex f71381c33c0..e262bbb8934 100644--- a/tools/approval_context.py+++ b/tools/approval_context.py@@ -33,6 +33,26 @@ _approval_session_id: contextvars.ContextVar[str] = _ctx("approval_session_id")# it onto the non-interactive auto-approve path so a dangerous command runs without the approval callback firing# (GHSA-96vc-wcxf-jjff). None = unset → env fallback._hermes_interactive_ctx: contextvars.ContextVar[str | None] = _ctx("hermes_interactive", None)+# CLI, TUI and Desktop turns hold their approval and clarify prompts open until the user answers or the turn is+# interrupted: the user is at the screen the prompt is painted on. Messaging platforms, ACP and plugin transports+# keep ``approvals.timeout`` — a push notification can sit unseen, and their buttons expire.+_prompts_wait_for_answer: contextvars.ContextVar[bool] = contextvars.ContextVar("prompts_wait_for_answer",+ default=False)+++def set_prompts_wait_for_answer() -> contextvars.Token[bool]:+ """Bind "built-in prompts wait until answered" for the current turn (CLI / TUI / Desktop)."""+ return _prompts_wait_for_answer.set(True)+++def reset_prompts_wait_for_answer(token: contextvars.Token[bool]) -> None:+ """Restore the prior value from :func:`set_prompts_wait_for_answer`."""+ _prompts_wait_for_answer.reset(token)+++def prompts_wait_for_answer() -> bool:+ """True when the current turn's built-in prompts have no deadline."""+ return _prompts_wait_for_answer.get()def set_hermes_interactive_context(interactive: bool) -> contextvars.Token:@@ -258,6 +278,16 @@ def _get_approval_timeout() -> int:return min(raw, safe_cap)+def approval_wait_seconds() -> int:+ """How long a built-in approval prompt stays open in this turn: until answered on CLI / TUI / Desktop+ (the platform-safe maximum, so ``Lock.acquire`` / ``Thread.join`` bounds derived from it stay valid),+ else ``approvals.timeout``."""+ if prompts_wait_for_answer():+ from agent.deadline import MAX_SAFE_TIMEOUT_S+ return int(MAX_SAFE_TIMEOUT_S)+ return _get_approval_timeout()++def format_approval_window(seconds: int) -> str:"""The ONE human wording for an approval timeout window, shared by the CLI timeout notice,the tool result's ``user_summary`` and the gateway card copy so every surface agrees:diff --git a/tools/approval_gateway_wait.py b/tools/approval_gateway_wait.pyindex c564997e815..841dccfa461 100644--- a/tools/approval_gateway_wait.py+++ b/tools/approval_gateway_wait.py@@ -43,8 +43,9 @@ class _ApprovalEntry:def _poll_event(event: threading.Event, session_key: str, *, interrupt_log: str) -> str:- """Wait on *event* until it fires, the turn is interrupted, or approvals.timeout- elapses; returns ``"set"`` | ``"interrupted"`` | ``"timeout"``. Polls in ~1s+ """Wait on *event* until it fires, the turn is interrupted, or the approval window+ elapses (``approval_wait_seconds``: until answered on TUI/Desktop, approvals.timeout+ on messaging platforms); returns ``"set"`` | ``"interrupted"`` | ``"timeout"``. Polls in ~1sslices so activity heartbeats reach the agent's inactivity tracker every ~10s —otherwise the gateway watchdog kills the agent while the user is stillresponding (mirrors ``_wait_for_process()`` cadence). The loop is recorded as@@ -55,7 +56,7 @@ def _poll_event(event: threading.Event, session_key: str, *, interrupt_log: str)per-thread interrupt-cause channel (``get_interrupt_reason()``, a trusted fixedcategory), never inferred from message text, so the caller can report awithdrawn prompt without inventing a user refusal."""- deadline = time.monotonic() + max(_ctx._get_approval_timeout(), 0)+ deadline = time.monotonic() + max(_ctx.approval_wait_seconds(), 0)heartbeat = activity_heartbeat("waiting for user approval")with human_wait_window(session_key):while True:diff --git a/tools/approval_human_wait.py b/tools/approval_human_wait.pyindex 4c8a1c1e3bb..b6f33fd7ecd 100644--- a/tools/approval_human_wait.py+++ b/tools/approval_human_wait.py@@ -28,11 +28,14 @@ import time# session's batch deadline. State is process-global like the rest of this module's approval state; entries# are bounded by _HUMAN_WAIT_MAX_SESSIONS.class _HumanWaitState:- __slots__ = ("pending", "window_started", "completed_seconds")+ __slots__ = ("pending", "window_started", "window_ceiling", "completed_seconds")def __init__(self) -> None:self.pending = 0self.window_started: float | None = None+ # Ceiling of the open window, fixed by the waiting threads when they enter it: the batch wait loop that+ # reads it may run in another context, where an unbounded CLI/TUI/Desktop prompt would look bounded.+ self.window_ceiling = 0.0self.completed_seconds = 0.0@@ -46,18 +49,19 @@ HUMAN_WAIT_MARGIN_S = 60.0def human_wait_ceiling() -> float:- """Max seconds a single window may contribute: approvals.timeout + margin.- Every legitimate human wait self-terminates at ``approvals.timeout`` (the CLI- prompt join and the gateway poll loop both enforce it), so a window that+ """Max seconds a single window may contribute in this turn: the approval window + margin.+ On messaging platforms every legitimate human wait self-terminates at+ ``approvals.timeout`` (the gateway poll loop enforces it), so a window thatoverstays this ceiling is itself wedged and must not keep extending a batch- deadline. Also the bound on the authorization gate's serialization-lock+ deadline; CLI/TUI/Desktop prompts wait until answered, so their ceiling is the+ platform-safe maximum. Also the bound on the authorization gate's serialization-lockacquire in agent/tool_executor.py, so the two cannot drift. Never call whileholding ``_human_wait_lock`` — it reads the config cache.- ``_get_approval_timeout`` caps at ``agent.deadline.MAX_SAFE_TIMEOUT_S`` so the+ ``approval_wait_seconds`` caps at ``agent.deadline.MAX_SAFE_TIMEOUT_S`` so thevalue is always safe for ``Lock.acquire(timeout=...)`` / ``Thread.join(timeout=...)``."""from tools import approval_contextfrom agent.deadline import MAX_SAFE_TIMEOUT_S- return min(MAX_SAFE_TIMEOUT_S, float(approval_context._get_approval_timeout()) + HUMAN_WAIT_MARGIN_S)+ return min(MAX_SAFE_TIMEOUT_S, float(approval_context.approval_wait_seconds()) + HUMAN_WAIT_MARGIN_S)def _clamped_window_seconds(started: float, now: float, ceiling: float) -> float:@@ -118,26 +122,29 @@ def human_wait_window(session_key: str | None = None):See #79719."""key = _resolve_key(session_key)+ ceiling = human_wait_ceiling()now = time.monotonic()with _human_wait_lock:state = _human_wait_state(key)if state.pending == 0:- state.window_started = now+ state.window_started, state.window_ceiling = now, ceiling+ else:+ state.window_ceiling = max(state.window_ceiling, ceiling)state.pending += 1try:yieldfinally:now = time.monotonic()- # Clamp the accrual too: a window that overstayed the ceiling was wedged —- # record at most the ceiling, not the whole overstay.- ceiling = human_wait_ceiling()with _human_wait_lock:state = _human_wait_states.get(key)if state is not None:state.pending -= 1if state.pending == 0:if state.window_started is not None:- state.completed_seconds += _clamped_window_seconds(state.window_started, now, ceiling)+ # Clamp the accrual too: a window that overstayed the ceiling was wedged —+ # record at most the ceiling, not the whole overstay.+ state.completed_seconds += _clamped_window_seconds(+ state.window_started, now, state.window_ceiling)state.window_started = None@@ -148,23 +155,16 @@ def human_wait_seconds(session_key: str | None = None) -> float:cap pressure, which can only shrink a consumer's baseline delta to zero (thesafe direction: the deadline fires sooner). Deadline consumers snapshot abaseline at batch start and use the delta. Each window's contribution is- clamped to :func:`human_wait_ceiling` (belt-and-braces against the- wedged-window hang).-- Each window's contribution is clamped to :func:`human_wait_ceiling`: every legitimate human wait- self-terminates at ``approvals.timeout`` (both the CLI prompt join and the gateway poll loop enforce- it), so a window that overstays that bound is itself wedged and must not keep extending a batch deadline- (belt-and-braces for #79719).+ clamped to the :func:`human_wait_ceiling` its waiters entered with+ (belt-and-braces against the wedged-window hang, #79719)."""key = _resolve_key(session_key)now = time.monotonic()- # Resolve the clamp outside the lock: it reads the config cache, which must never nest under _human_wait_lock.- ceiling = human_wait_ceiling()with _human_wait_lock:state = _human_wait_states.get(key)if state is None:return 0.0total = state.completed_secondsif state.window_started is not None:- total += _clamped_window_seconds(state.window_started, now, ceiling)+ total += _clamped_window_seconds(state.window_started, now, state.window_ceiling)return totaldiff --git a/tools/approval_prompt.py b/tools/approval_prompt.pyindex 85129a16a91..eaff586cfbc 100644--- a/tools/approval_prompt.py+++ b/tools/approval_prompt.py@@ -44,8 +44,8 @@ def prompt_dangerous_approval(command: str, description: str, timeout_seconds: iSee #81887."""if timeout_seconds is None:- timeout_seconds = _ctx._get_approval_timeout()- # Everything below is a human prompt (callback panel or input() fallback, both bounded by the approval deadline):+ timeout_seconds = _ctx.approval_wait_seconds()+ # Everything below is a human prompt (callback panel or input() fallback, both bounded by the approval window):# record it as human-wait time so the concurrent batch deadline excludes it.# See #79719.with human_wait_window():